I have a ContextMenu defined in XAML and I modify it in code:
ContextMenu EditContextMenu;
EditContextMenu = (ContextMenu)this.FindResource("EditContextMenu");
//Modify it here...
Then, I need to set it as a ContextMenu for all TextBoxes, DatePickers, etc in a XAML theme file using data binding. I’ve tried adding a property to the main window :
public ContextMenu sosEditContextMenu
{
get
{
return EditContextMenu;
}
}
…and binding it like this (the folowing is from a theme file with ‘FTWin‘ being the Name of my main window where the sosEditContextMenu property is defined):
<Style TargetType="{x:Type TextBox}">
<Setter Property="ContextMenu" Value="{Binding Source=FTWin, Path=sosEditContextMenu}"/>
</Style>
…but it doesn’t work. I’ve tried various things and I either got Exceptions about resources not being found or nothing happened.
Is what I’m trying to do possible and, if yes, what am I doing wrong?
I don’t know if setting the DataContext of an object could help, but setting it for all TextBoxes by code is not so nice right?
Put the menu that you defined in xaml in a resource dictionary that can be seen from the textbox and instead of using a binding just use StaticResource to link it in your style.
You can still change it in code behind by looking for the resource