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 Dic
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 ResourceDictionary and name it ResourceDictionaryName.xaml.cs. It will become the code-behind file for your ResourceDictionary.
Open the new .cs file, and make sure the following is there (Can't remember if it's added automatically or not):
public partial class ResourceDictionaryName
{
public ResourceDictionaryName()
{
InitializeComponent();
}
}
Next, open your XAML file and add the following x:Class attribute to the ResourceDictionary Tag:
<ResourceDictionary x:Class="MyNamespace.ResourceDictionaryName" ... />
Now your ResourceDictionary is 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:
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
var cbx = sender as CheckBox;
MyViewModel viewModel = (MyViewModel)cbx.DataContext;
}
If CheckBox's DataContext is not the ViewModel you're looking for:
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
var cbx = sender as CheckBox;
var userControl = FindAncestor<MyUserControl>(cbx);
MyViewModel viewModel = (MyViewModel)myUserControl.DataContext;
}
public static T FindAncestor<T>(DependencyObject current)
where T : DependencyObject
{
current = VisualTreeHelper.GetParent(current);
while (current != null)
{
if (current is T)
{
return (T)current;
}
current = VisualTreeHelper.GetParent(current);
};
return null;
}