After looking around on StackOverflow and other websites, I can see that people have a lot of problems with binding properties and commands to MenuItems
and ContextMenus
because ContextMenu
is not part of the WPF visual tree. Anyway, I've tried a few different solutions and am not having any luck.
I have a MenuItem
that is part of a ContextMenu
. The ContextMenu
is part of a window that is bound to a ViewModel in its code behind like so:
public partial class Window1 : Window
{
public MainWindowViewModel ViewModel { get { return DataContext as MainWindowViewModel; } }
public Window1()
{
InitializeComponent();
//There is a property in the App.xaml.cs file that refers to MainWindowViewModel
DataContext = App.MainWindowViewModel = new MainWindowViewModel();
}
}
The property that I am trying to bind to in MainWindowViewModel
:
private bool _askBeforeDownloading_Checked = true;
public bool AskBeforeDownloading_Checked
{
get { return _askBeforeDownloading_Checked; }
set
{
_askBeforeDownloading_Checked = value;
NotifyPropertyChange(() => AskBeforeDownloading_Checked);
}
}
My current attempt in XAML:
<Button Name="Button_1" >
<Button.ContextMenu>
<ContextMenu x:Name="MainContextMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" >
<MenuItem >
<MenuItem IsCheckable="True" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget.AskBeforeDownloading_Checked}" />
</MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
I came up with my current XAML based on the accepted answer on this question, along with this guide. What am I missing? I'm not getting any output errors, but the MenuItem
is not getting checked. Is there something that I am not doing with PlacementTarget
?
Update: I thought it would be important to note that my ContextMenu
is a child control of a Button
. I've added it to my XAML.
Update 2: After using Snoop on my application I found that my Button
was automatically inheriting from MainWindowViewModel
as it should. However, I overlooked a parent MenuItem
that may affect my code. I've updated my XAML and apologize for missing that the first time.