上下文菜单绑定到父窗口的数据上下文 [英] Context Menu Binding to Parent Window's Datacontext
问题描述
我有一个 TreeListControl 绑定到我的 VM 中的集合.我还想在 treelistcontrol 中定义上下文菜单,使其标题文本绑定到我的 VM 中的另一个字符串.在这种情况下如何设置数据上下文?我试着
I have a TreeListControl that binds to a collection in my VM. I also want to define the context menu inside the treelistcontrol having its header text bind to another string in my VM. how can I set the data context in this case? I tried to
<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>
但它不起作用.
这是视图模型
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";
}
推荐答案
为您的窗口提供一个名称并明确绑定到它,例如
Provide a name for your window and explicitly bind to it such as
<window x:Name="ReportsPage"/>
...
<MenuItem DataContext="{Binding ElementName=ReportsPage}"/>
<小时>
更新
因为上下文菜单实际上在它自己的窗口中,所以绑定有点棘手.因此,最好的办法是将 RelativeSource
走上上下文的父级并从那里拉出标题文本:
Since the context menu is actually in its own window, binding is a bit trickier. Hence the best bet is to walk up the RelativeSource
to the context's parent 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>
对于这个上下文产生这个
Which for this context produces this
这篇关于上下文菜单绑定到父窗口的数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!