I’m trying to set a ResourceDictionary DataContext, from the code behind of my Resource Dictionary.
I have a Data Template that uses its own style (the Resource Dictionary), the style contains a checkbox with its own style :
<Style x:Key="CheckBoxStyle" TargetType="CheckBox">
<EventSetter Event="CheckBox.Checked" Handler="CheckBox_Checked"/>
<EventSetter Event="CheckBox.Unchecked" Handler="CheckBox_Unchecked"/>
</Style>
In the CheckBox_Checked event, I want to reference the dictionary’s parent (a User Control) View Model, to execute a function, but because Resource Dictionaries do not have a DataContext property setting the DataContext from inside a control event, like this :
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
MyViewModel viewModel = (MyViewModel)DataContext;
}
doesn’t work (of course).
I think I need to get a handle to the Ancestor (the Resource Dictionary User Control), but don’t know how to do this – or there may be another way..
Thanks
Joe
As @dowhilefor’s comment says, Resource Dictionaries are simply a collection of resources, so do not need a DataContext. You can, however, add a code-behind file to the ResourceDictionary, which may be what you’re looking for.
Create a new class in the same directory as your
ResourceDictionaryand name it ResourceDictionaryName.xaml.cs. It will become the code-behind file for yourResourceDictionary.Open the new .cs file, and make sure the following is there (Can’t remember if it’s added automatically or not):
Next, open your XAML file and add the following
x:Classattribute to theResourceDictionaryTag:Now your
ResourceDictionaryis actually a class, and can have a code-behind file.Edit
In response to your edits, I would use the CheckBox itself and get either the CheckBox’s DataContext, or traverse up the Visual Tree to find the UserControl I’m looking for and then get it’s Data Context
Easy way:
If CheckBox’s DataContext is not the ViewModel you’re looking for: