Trouble finding ViewModel property from ListView - binding

I have a rather complicated data binding template and I'm not able to find away back to my ViewModel to access a property and command.
This is how my xaml is set up from Top to Bottom as its layout:
<HierarchicalDataTemplate x:Key="ChapterReferencesTemplate">
<StackPanel>
<DockPanel>
<TextBlock Text="Chapter Reference "/>
<AccessText Text="{Binding Path=Chapter}" />
</DockPanel>
<DockPanel>
<TextBlock Text="Total Reference Verses "/>
<AccessText Text="{Binding Path=Verses}" />
</DockPanel>
<ListView Name="VerseReferencesListView" Height="200"
ItemsSource="{Binding Path=VerseReferences}"
SelectedItem="{Binding Path=DataContext.CurrentVerseReference, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:CreateWritingsViewModel}}}"
AlternationCount="2"
BorderThickness="0"
IsSynchronizedWithCurrentItem="True">
<ListView.View>
<GridView AllowsColumnReorder="true" ColumnHeaderToolTip="xmlNamespace List" >
<GridViewColumn
Header="Verse"
DisplayMemberBinding="{Binding Path=Verse}" Width="Auto">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Width="Auto" TextAlignment="Left" Text="{Binding}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn
Header="Query"
DisplayMemberBinding="{Binding Path=Query}" Width="Auto">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Width="Auto" TextAlignment="Left" Text="{Binding}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Actions">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button
Command="{Binding Path=DataContext.LookupReferencesCommand, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type src:CreateWritingsViewModel}}}"
CommandParameter="{Binding .}"
Template="{StaticResource AddButtonTemplate}" Cursor="Hand" Width="30"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
<HierarchicalDataTemplate x:Key="WritingsReferenceTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="200"/>
</Grid.ColumnDefinitions>
<GroupBox Header="{Binding Path=Hebrew}">
<StackPanel Margin="5 10 5 0">
<StackPanel>
<DockPanel>
<TextBlock Text="Writings of "/>
<AccessText Text="{Binding Path=Writings}" />
</DockPanel>
<DockPanel>
<TextBlock Text="Total Reference Chapters : "/>
<AccessText Text="{Binding Path=Chapters}" />
</DockPanel>
<DockPanel>
<TextBlock Text="Total Reference Verses : "/>
<AccessText Text="{Binding Path=Verses}" />
</DockPanel>
<DockPanel >
<TextBlock Text="Query for Writing : "/>
<AccessText Text="{Binding Path=QueryWriting}" />
</DockPanel>
<DockPanel >
<TextBlock Text="Query for Chapters : "/>
<AccessText Text="{Binding Path=QueryChapters}" />
</DockPanel>
</StackPanel>
<DockPanel Margin="0 5 0 0">
<GroupBox Header="Chapter References">
<Expander>
<ScrollViewer VerticalScrollBarVisibility="Auto" Height="200">
<HeaderedItemsControl
ItemTemplate="{StaticResource ChapterReferencesTemplate}"
ItemsSource="{Binding Path=ChapterReferences}"
Margin="10,0,0,0" />
</ScrollViewer>
</Expander>
</GroupBox>
</DockPanel>
</StackPanel>
</GroupBox>
</Grid>
<GroupBox Grid.Column="1" Header="CREATE REFERENCES">
<ListBox
Name="ReferenceListBox"
ItemTemplate="{StaticResource WritingsReferenceTemplate}"
ItemsSource="{Binding Path=odsDocumentsService.WritingsReferenceItems}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
VirtualizingStackPanel.IsVirtualizing="False"
VirtualizingStackPanel.VirtualizationMode="Standard">
</ListBox>
In my HierarchicalDataTemplate x:Key="ChapterReferencesTemplate" as you can see I'm already binding to ItemsSource="{Binding Path=VerseReferences}" but I also need to bind to my ViewModel's CurrentVerseReference for the SelectedItem property of the ListView.
Same for my Button Command to my ViewModel's LookupReferencesCommand. All the data is coming from bindings to a object class that contains a ObservableCollection (ChapterReferences, VerseReferences) So far I'm having no success in getting this to work and would appreciate your help very much.
Thanks!...

Well, I found the right properties to use to get this to work. But, I need to do some reading to find out more about these property settings. For my SelectedItem I had to do this:
SelectedItem="{Binding Path=DataContext.CurrentVerseReference, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
And for my Button Command and CommandParameter I had to do this and this is where I need to do more reading to understand how this worked:
<Button Command="{Binding Path=DataContext.LookupReferencesCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}, AncestorLevel=2, Mode=FindAncestor}}"
CommandParameter="{Binding Path=DataContext.CurrentVerseReference, RelativeSource={RelativeSource AncestorType={x:Type ListBox}, AncestorLevel=2, Mode=FindAncestor}}"
Template="{StaticResource AddButtonTemplate}" Cursor="Hand" Width="30"/>
Its the AncestorLevel I don't understand. I'm assuming its because I have the Button control at the second level of the ListView?

Related

Xamarin Forms Binding to Parent Control

I'm building a Xamarin Forms application and am trying to reference the binding context of a parent control from a DataTemplate:
<flv:FlowListView Grid.Row="3" x:Name="abc"
Grid.Column="0"
Grid.ColumnSpan="2"
FlowColumnCount="3"
SeparatorVisibility="None"
HasUnevenRows="true"
FlowItemsSource="{Binding ProductPackageBatch}"
FlowLastTappedItem="{Binding LastTappedItem}"
FlowItemTappedCommand="{Binding ItemTappedCommand}">
<flv:FlowListView.FlowColumnTemplate>
<DataTemplate>
<StackLayout Margin="5, 10, 10, 5">
<StackLayout.Children>
<Frame Padding="2"
OutlineColor="{DynamicResource ProductGridImageBorderColor}"
HasShadow="False"
BackgroundColor="{DynamicResource ProductGridBackgroundColor}">
<Image Aspect="AspectFit"
WidthRequest="100"
Source="{Binding ImageBase64, Converter={StaticResource Base64ToImageConverter}}">
<Image.HeightRequest>
<OnPlatform x:TypeArguments="x:Double"
iOS="100"
Android="150" />
</Image.HeightRequest>
</Image>
</Frame>
<Label Style="{StaticResource ProductGridName}"
Text="{Binding Name}" />
<Label Style="{StaticResource ProductGridFormattedPrice}"
Text="{Binding FormattedPrice}"
FontAttributes="Bold" />
<Button BackgroundColor="{DynamicResource BuyButtonColor}"
TextColor="{DynamicResource TextColor}"
BorderRadius="0"
Margin="5, 0, 5, 0"
VerticalOptions="End"
Text="Buy"
Command="{Binding Source={x:Reference abc}, Path=BindingContext.AddToUserCartCommand}"
CommandParameter="{Binding .}" />
</StackLayout.Children>
</StackLayout>
</DataTemplate>
</flv:FlowListView.FlowColumnTemplate>
</flv:FlowListView>
There is an event called on AddToUserCartCommand that I want to call from a button in the FlowListView. I've tried a few different ways to reference the control, but the method never gets called. The following button sits outside this control and works ok:
<Button Grid.Row="4"
Margin="30"
BackgroundColor="{DynamicResource BuyButtonColor}"
TextColor="{DynamicResource TextColor}"
BorderRadius="0"
Text="Add to Cart"
Command="{Binding AddToUserCartCommand}"
CommandParameter="{Binding ProductPackage.Id}" />
Can anyone help explain what I'm doing wrong?
Set the correct binding context of the Command and CommandParamter:
<Button BackgroundColor="{DynamicResource BuyButtonColor}"
BindingContext="{x:Reference Name=abc}"
TextColor="{DynamicResource TextColor}"
BorderRadius="0"
Margin="5, 0, 5, 0"
VerticalOptions="End"
Text="Buy"
Command="{Binding Path=BindingContext.AddToUserCartCommand}"
CommandParameter="{Binding Path=BindingContext.ProductPackage.Id}" />

ListBox in Grid not resize in SplitView

I have problem with resize gridlayout.
This is man page:
This page has ListBox in 3 column. But when I fill in the data my ListBox I don't see my buttons and scrollbar. I have ScrollBar in ScrollViewer but it doesn't work. I generate all values in For loop (100 items). For now I have something like this:
This is my code of page:
<Page
x:Class="MemoryWords.LernWords"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MemoryWords"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="mainPage">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="4*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" x:Name="LayoutRoot">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width=".5*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Name="WordBeforeTranslation"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20"/>
<StackPanel Grid.Column="1" >
<TextBlock Name="WordAfterTranslation"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20"/>
<TextBlock Name="WordArticulation"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20"/>
</StackPanel>
<ScrollViewer Grid.Column="2">
<ListBox Name="AllWords"/>
</ScrollViewer>
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Content="Previous"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<Button Grid.Column="1"
Content="Check"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<Button Grid.Column="2"
Content="Next"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Name="BtnLoadFile"
Click="BtnLoadFile_Click"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="Load file"/>
<Button Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="New Random"/>
<Button Grid.Column="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="--------"/>
</Grid>
</Grid>
</Page>
Next case:
How I can set on starting, my grid filled all content of page without loaded data to ListBox? And Can I resize my app without lost of content? I don't want set permanent values to height and width. I would like have only layouts without permanent values. Generally, I would like when I will rescale app, my grid will by have similar layout.
I would like to make my page look like as on first my screenshot.
Is it possible?
EDIT:
This is my code from MainPage:
<Page
x:Class="MemoryWords.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MemoryWords"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel>
<CommandBar HorizontalAlignment="Left">
<AppBarButton Label="Menu" Click="ToogleMenu_Click">
<AppBarButton.Icon>
<FontIcon FontFamily="Segoe MDL2 Assets" Glyph=""/>
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton Icon="Back" Label="Back" Click="GoBack_Click"/>
<AppBarButton Icon="Home" Label="Play" Click="GoHome_Click"/>
</CommandBar>
<!--<Button Content="Open" Click="Button_Click"/>-->
<SplitView Name="MySplitView"
DisplayMode="CompactOverlay"
CompactPaneLength="50"
OpenPaneLength="200">
<SplitView.Pane >
<StackPanel>
<ListBox SelectionMode="Single"
Name="ListOfMenu"
SelectionChanged="ListOfMenu_SelectionChanged">
<ListBoxItem Name="LearnWordsItem">
<StackPanel Orientation="Horizontal">
<TextBlock FontFamily="Segoe MDL2 Assets"
Text=""
FontSize="30"
MinWidth="50"/>
<TextBlock Text="Nauka słówek"/>
</StackPanel>
</ListBoxItem>
<ListBoxItem Name="SettingItem">
<StackPanel Orientation="Horizontal">
<TextBlock FontFamily="Segoe MDL2 Assets"
Text=""
FontSize="30"
MinWidth="50"/>
<TextBlock Text="Ustawienia"/>
</StackPanel>
</ListBoxItem>
</ListBox>
</StackPanel>
</SplitView.Pane>
<SplitView.Content>
<StackPanel>
<Frame Name="MyFrame">
</Frame>
</StackPanel>
</SplitView.Content>
</SplitView>
</StackPanel>
</Page>
I saw that you've set three RowDefinition as "*", it certainly will drive out those buttons. If you want to make these buttons always show there, you need to set fixed height for the two rows. See the following code:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="100" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" x:Name="LayoutRoot">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width=".5*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Name="WordBeforeTranslation"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20" />
<StackPanel Grid.Column="1">
<TextBlock Name="WordAfterTranslation"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20" />
<TextBlock Name="WordArticulation"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20" />
</StackPanel>
<ScrollViewer Grid.Column="2">
<ListBox Name="AllWords" />
</ScrollViewer>
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Content="Previous"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
<Button Grid.Column="1"
Content="Check"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
<Button Grid.Column="2"
Content="Next"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Name="BtnLoadFile"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="Load file" />
<Button Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="New Random" />
<Button Grid.Column="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="--------" />
</Grid>
</Grid>
Ok, I found answer on my question. :) Yeeee :)
My mistake was that in mainPage I didn't contained all in the grid.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<CommandBar Grid.Row="0" HorizontalAlignment="Left">
<AppBarButton Label="Menu" Click="ToogleMenu_Click">
<AppBarButton.Icon>
<FontIcon FontFamily="Segoe MDL2 Assets" Glyph=""/>
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton Icon="Back" Label="Back" Click="GoBack_Click"/>
<AppBarButton Icon="Home" Label="Play" Click="GoHome_Click"/>
</CommandBar>
<SplitView Grid.Row="1" Name="MySplitView"
DisplayMode="CompactOverlay"
CompactPaneLength="50"
OpenPaneLength="200"
VerticalAlignment="Stretch">
<SplitView.Pane >
<StackPanel>
<ListBox SelectionMode="Single"
Name="ListOfMenu"
SelectionChanged="ListOfMenu_SelectionChanged">
<ListBoxItem Name="LearnWordsItem">
<StackPanel Orientation="Horizontal">
<TextBlock FontFamily="Segoe MDL2 Assets"
Text=""
FontSize="30"
MinWidth="50"/>
<TextBlock Text="Nauka słówek"/>
</StackPanel>
</ListBoxItem>
<ListBoxItem Name="SettingItem">
<StackPanel Orientation="Horizontal">
<TextBlock FontFamily="Segoe MDL2 Assets"
Text=""
FontSize="30"
MinWidth="50"/>
<TextBlock Text="Ustawienia"/>
</StackPanel>
</ListBoxItem>
</ListBox>
</StackPanel>
</SplitView.Pane>
<SplitView.Content>
<Frame Name="MyFrame" >
</Frame>
</SplitView.Content>
</SplitView>
</Grid>
Enough to change StackPanel on Grid. That is all.

Binding fails when moved into a flyout

I have a slider bound to the volume property of a MediaElement. This works if marked up as below:
<UserControl
x:Class="GenTest.VideoElement"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:GenTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="600">
<UserControl.Resources>
<Style x:Name="transportStyle" TargetType="Button">
<Setter Property="Height" Value="40" />
<Setter Property="Width" Value="75" />
<Setter Property="FontSize" Value="11" />
</Style>
<Style x:Name="atransportStyle" TargetType="AppBarButton">
<Setter Property="IsCompact" Value="true" />
<Setter Property="FontSize" Value="11" />
</Style>
</UserControl.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<ContentControl x:Name="videoContainer"
KeyUp="VideoContainer_KeyUp"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Height="400" Grid.Row="0" >
<MediaElement Name="videoMediaElement"
MediaOpened="videoElement_MediaOpened"
MediaEnded="videoMediaElement_MediaEnded"
MediaFailed="videoMediaElement_MediaFailed"
CurrentStateChanged="videoMediaElement_CurrentStateChanged"
AutoPlay="False" />
</ContentControl>
<!-- Transport Controls -->
<StackPanel Name="TransportControlsPanel"
HorizontalAlignment="Center"
Grid.Row="1" >
<Slider Name="timelineSlider" Margin="0,0" Width="500" Height="37"/>
<StackPanel Orientation="Horizontal">
<AppBarButton x:Name="btnPlay" Icon="Play" Click="btnPlay_Click" Style="{StaticResource atransportStyle}" Label="Play"/>
<AppBarButton x:Name="btnStop" Icon="Stop" Click="btnStop_Click" Style="{StaticResource atransportStyle}"/>
<AppBarButton x:Name="btnReverse" Icon="Previous" Click="btnReverse_Click" Style="{StaticResource atransportStyle}"/>
<AppBarButton x:Name="btnForward" Icon="Next" Click="btnForward_Click" Style="{StaticResource atransportStyle}"/>
<Button Name="btnFullScreenToggle" Click="btnFullScreenToggle_Click"
Style="{StaticResource transportStyle}" Content="Full" />
<ComboBox Name="cbAudioTracks"
SelectionChanged="cbAudioTracks_SelectionChanged"
Width="75" />
<AppBarButton x:Name="btnTest" Icon="Other" Style="{StaticResource atransportStyle}">
<AppBarButton.Flyout>
<Flyout>
<StackPanel Orientation="Vertical">
</StackPanel>
</Flyout>
</AppBarButton.Flyout>
</AppBarButton>
<Slider Minimum="0" Maximum="1" StepFrequency="0.1" Height="100" Value="{Binding Mode=TwoWay,
ElementName=videoMediaElement, Path=Volume}" Orientation="Vertical"/>
</StackPanel>
</StackPanel>
</Grid>
</UserControl>
But when I put the slider into the Flyout the Binding no longer works.
<AppBarButton x:Name="btnTest" Icon="Other" Style="{StaticResource atransportStyle}">
<AppBarButton.Flyout>
<Flyout>
<StackPanel Orientation="Vertical">
<Slider Minimum="0" Maximum="1" StepFrequency="0.1" Height="100" Value="{Binding Mode=TwoWay,
ElementName=videoMediaElement, Path=Volume}" Orientation="Vertical"/>
</StackPanel>
</Flyout>
</AppBarButton.Flyout>
</AppBarButton>
There are no errors and I cant do a Binding trace because the TraceListeners have been removed from WinRt. I have tried:
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
this.UnhandledException += App_UnhandledException;
DebugSettings.BindingFailed += OnDebugSettingsOnBindingFailed;
}
private void OnDebugSettingsOnBindingFailed(object sender, BindingFailedEventArgs args)
{
new MessageDialog(args.Message).ShowAsync();
}
But no errors are thrown and there is nothing in the output window. In design mode, using the Properties Windows, if i change the volume value of the videoMediaElement then the Value property of the Slider changes but I cant update the Value of the slider, it's read only.
I can make it work within the flyout if I use code:
private void RangeBase_OnValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
var slider = sender as Slider;
videoMediaElement.Volume = slider.Value;
}
but then why bother with bindings at all?
I had this kind of errors some times now, I think that Flyouts are handled separately where the Bindings can't look for the ElementName.
I suggest that you should do this with a ViewModel, instead of cross binding in your Page
Slider.Value [TwoWay-Bind] -> ViewModel.Volume
ViewModel.Volume -> videoMediaElement.Volume

Binding ContextMenu defined in a DataTemplate to command

Ok, here is my problem: I have a UserControl Template defined in Style.xaml like this
<Style x:Key="ModulProfTemplate" TargetType="{x:Type UserControl}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type UserControl}">
<Border BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" BorderThickness="{TemplateBinding BorderThickness}" DataContext="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}">
<Border x:Name="border" BorderBrush="#004E6CA9" BorderThickness="1.5">
<Grid x:Name="Layout" Background="{Binding Background, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0.5" DataContext="{Binding}">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Disponibil" Command="{Binding GridContextMenuCommand}" CommandParameter="disp"/>
<MenuItem Header="Indisponibil" Command="{Binding GridContextMenuCommand}" CommandParameter="indisp"/>
</ContextMenu>
</Grid.ContextMenu>
<Grid.RowDefinitions>
<RowDefinition Height="0.497*"/>
<RowDefinition Height="0.5*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" d:LayoutOverrides="Height" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock TextWrapping="Wrap" Text="{Binding SalaSaptPara, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock TextWrapping="Wrap" Text="{Binding MaterieSaptPara, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock TextWrapping="Wrap" Text="{Binding SalaSaptImpara, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock TextWrapping="Wrap" Text="{Binding MaterieSaptImpara, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2,0,0,0"/>
</StackPanel>
</Grid>
</Border>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" TargetName="border" Value="#CA4E6CA9"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
the problem is that i don't know how to bind the command to menuitem. The UserControl's DataContext is set to ViewModel.Luni.M1, and the command is in ViewModel DataContext. So my question is: How do i change the DataContext so i can bind the command?
Solved, all i had to do was add a tag to the border that was bound to my viewmodel's datacontext, and after that use PlacementTarget.Tag.MyCommand, as shown like this :)
<Border x:Name="border" BorderBrush="#004E6CA9" BorderThickness="1.5" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:CadreDidacticeView, AncestorLevel=1}, Path=DataContext}">
<Border.ContextMenu>
<ContextMenu>
<MenuItem Header="Disponibil" Command="{Binding PlacementTarget.Tag.GridContextMenuCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}">
</MenuItem>
</ContextMenu>
</Border.ContextMenu>

Set the datacontext of the context menu with in a data template

Below is the code snippet:
<ResourceDictionary>
* * *
<DataTemplate x:Key="xyzTemplate" DataType="arguments" PresentationTraceSources.TraceLevel="High">
<StackPanel Orientation="Horizontal">
<TextBlock Text="(" VerticalAlignment="Center" Margin="2,0,2,0" FontSize="18"
x:Name="firstbrace" Visibility="Collapsed">
</TextBlock>
<ItemsControl ItemsSource="{Binding}" KeyboardNavigation.IsTabStop="False">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock
FontSize="11" VerticalAlignment="Bottom" Margin="1,0,1,2" Text=" , " Width="auto" Name="Comma" Height="auto" >
</TextBlock>
<ComboBox x:Name="blockCombo" Visibility="Collapsed" ItemsSource="{Binding XPath=.//value}" >
<ComboBox.ContextMenu>
<ContextMenu x:Name="xyzcontextMenu"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.DataContext}"
>
<MenuItem
Command="{Binding Path=xyzcommand}"
Header="MenuItem1" >
</MenuItem>
</ContextMenu>
</ComboBox.ContextMenu>
</ComboBox>
I need to set the data context of the context menu "xyzcontextmenu" as the data context of the UserControl.
Please let me know asap how can I achieve this
Thanks,
Shwetha

Resources