Associating a context menu with a parent Datacontext window

I have a TreeListControl that binds to a collection in my virtual machine. I also want to define a context menu inside the treelistcontrol by linking its header text to another line in my virtual machine. how can i set the data context in this case? I tried

<Window.DataContext> <model:ViewModel></model:ViewModel> </Window.DataContext> <Grid> <Button Grid.Row="1" Command="{Binding CellCheckedCommand}"></Button> <TextBlock Text="{Binding HeaderText}" Grid.Row="2"> <TextBlock.ContextMenu> <ContextMenu> <MenuItem DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext}" Header="{Binding HeaderText}"></MenuItem> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> </Grid> 

but that will not work.

Here is the ViewModel

 public DelegateCommand CellCheckedCommand { get; set; } private String _HeaderText; public String HeaderText { get { return _HeaderText; } set { _HeaderText = value; NotifyPropertyChanged("HeaderText"); } } public void NotifyPropertyChanged(String name) { if(PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } private void CellCheckedMethod() { HeaderText = "Changed"; } 
+2
wpf binding datacontext
Oct 14 '14 at 10:55
source share
2 answers

Provide a name for your window and explicitly bind to it, for example

 <window x:Name="ReportsPage"/> ... <MenuItem DataContext="{Binding ElementName=ReportsPage}"/> 



UPDATE

Since the context menu is actually located in its own window, binding is a bit more complicated. Therefore, it is best to approach the RelativeSource to the parent context and pull the header text from there:

  <Window.DataContext> <local:MainVM HeaderText="Jabberwocky" /> </Window.DataContext> ... <TextBlock Text="{Binding HeaderText}"> <TextBlock.ContextMenu> <ContextMenu> <MenuItem Header="{Binding Path=Parent.DataContext.HeaderText, RelativeSource={RelativeSource Self}}" /> </ContextMenu> </TextBlock.ContextMenu> 

What for this context creates this

enter image description here

+3
Oct. 15 '14 at 13:10
source share

This binds to Window :

 DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 

If the AddItemCommand command and the AddItemCommand property AddItemText defined on the Window ViewModel , bind to the Window DataContext :

 DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext}" 
+2
Oct 14 '14 at 11:27
source share



All Articles