简体   繁体   English

IsChecked绑定在ContextMenu的MenuItem中不起作用

[英]IsChecked Binding not working in MenuItem in a ContextMenu

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,然后按以下方式设置Items(此处仅一项,因为它无关紧要):

<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! 我在ContextMenu所在的GridView中的SelectionChanged上调用ContextMenu之前进行了设置。尽管SaveToDbOneChecked设置为true,但它不会在MenuItem的文本旁边显示选中的符号! I don'T know where i do something wrong and hope that somebody can help me here. 我不知道我在哪里做错了,希望有人可以在这里帮助我。

A few things you have to do to make this work. 为了使这项工作必须要做的几件事。 First of all you cannot bind from inside a MenuItem using ElementName property since the target element is most often out of your scope. 首先,由于目标元素通常不在您的范围内,因此您无法使用ElementName属性从MenuItem内部进行绑定。

If I understand correctly the Model is your ViewModel property, in this case all you have to do is to set it as the DataContext of the Element on which the ContextMenu is placed. 如果我正确理解Model是您的ViewModel属性,在这种情况下,您要做的就是将其设置为放置ContextMenu的Element的DataContext This will set the same DataContext for your MenuItem and you can bind directly to DataContext : 这将为您的MenuItem设置相同的DataContext ,并且您可以直接绑定到DataContext

IsChecked="{Binding SaveToDbOneChecked, Mode=TwoWay}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM