Set a ResourceDictionary DataContext from code behind

后端 未结 1 432
甜味超标
甜味超标 2021-01-14 05:03

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

相关标签:
1条回答
  • 2021-01-14 05:40

    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;
    }
    
    0 讨论(0)
提交回复
热议问题