Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsChecked Binding not working in MenuItem in a ContextMenu

I have an MVVM Application and want to add a ContextMenu.

I added the ContextMenu to XAML and then set the Items like this (only one item here because it doesn'T matter):

<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:

    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.

like image 391
Flo Avatar asked Dec 11 '13 14:12

Flo


1 Answers

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.

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. This will set the same DataContext for your MenuItem and you can bind directly to DataContext:

IsChecked="{Binding SaveToDbOneChecked, Mode=TwoWay}"
like image 82
Novitchi S Avatar answered Nov 01 '22 14:11

Novitchi S