wpf IsChecked 绑定在 ContextMenu 的 MenuItem 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20522228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IsChecked Binding not working in MenuItem in a ContextMenu
提问by Flo
I have an MVVM Application and want to add a ContextMenu.
我有一个 MVVM 应用程序,想添加一个 ContextMenu。
I added the ContextMenu to XAML and then set the Items like this (only one item here because it doesn'T matter):
我将 ContextMenu 添加到 XAML,然后像这样设置项目(这里只有一个项目,因为它无关紧要):
<MenuItem Header="{x:Static Monitor:MonitorResources.R0206_SaveLatestValueToDatabase}"
IsCheckable="true"
IsChecked="{Binding ElementName=root, Path=Model.SaveToDbOneChecked}"
IsEnabled="{Binding ElementName=root, Path=Model.SaveToDbOneEnabled}">
The SaveToDbOneChecked and SaveToDbOneEnabled are Properties in my Model which are implemented like this:
SaveToDbOneChecked 和 SaveToDbOneEnabled 是我模型中的属性,它们的实现方式如下:
private bool mSaveToDbOneEnabled;
public bool SaveToDbOneChecked
{
get { return mSaveToDbOneChecked; }
set { mSaveToDbOneChecked = value; OnPropertyChanged("SaveToDbOneChecked"); }
}
I set these before the ContextMenu gets called on the SelectionChanged in the GridView the ContextMenu is in. But it won't show the Checked sign next to the text of the MenuItem although the SaveToDbOneChecked has been set to true! I don'T know where i do something wrong and hope that somebody can help me here.
我在 ContextMenu 在 ContextMenu 所在的 GridView 中的 SelectionChanged 上调用 ContextMenu 之前设置了这些。但它不会在 MenuItem 的文本旁边显示 Checked 符号,尽管 SaveToDbOneChecked 已设置为 true!我不知道我哪里做错了,希望有人能在这里帮助我。
采纳答案by Novitchi S
A few things you have to do to make this work. First of all you cannot bind from inside a MenuItemusing ElementNameproperty since the target element is most often out of your scope.
您必须做一些事情才能使这项工作发挥作用。首先,您不能从MenuItemusingElementName属性内部进行绑定,因为目标元素通常超出您的范围。
If I understand correctly the Modelis your ViewModelproperty, in this case all you have to do is to set it as the DataContextof the Element on which the ContextMenuis placed.
This will set the same DataContextfor your MenuItemand you can bind directly to DataContext:
如果我理解正确,这Model是您的ViewModel财产,在这种情况下,您所要做的就是将其设置为放置DataContext的元素的ContextMenu。这将为您设置相同DataContext的MenuItem,您可以直接绑定到 DataContext:
IsChecked="{Binding SaveToDbOneChecked, Mode=TwoWay}"

