【发布时间】:2014-12-09 03:29:32
【问题描述】:
我有一个 TreeListControl 绑定到我的 VM 中的一个集合。我还想在 treelistcontrol 中定义上下文菜单,使其标题文本绑定到我的 VM 中的另一个字符串。在这种情况下如何设置数据上下文?我试过了
<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";
}
【问题讨论】:
-
您正在与两件事作斗争,上下文菜单 (cm) 的性质及其所在的父级。单独的 CM 可以绑定到其内部视觉树之外。但是一旦 CM 被放置在一个没有可视化树的对象上(就像树列表或数据网格上的某些项目),人们现在正在努力寻找页面的可视化树。您已经了解了绑定,但每个控件都有自己的特点。也许扩展树项的数据类以指向当前VM(?)。这样绑定就可以访问当前的虚拟机,而不必费劲。
-
最简洁的绑定文字可以在MSDN上找到:Data Binding Overview
标签: wpf c#-4.0 binding datacontext