WPF: Find Resources from UserControl within DataTemplateSelector class

后端 未结 1 742
既然无缘
既然无缘 2021-02-09 23:37

I know there is this thread: How to find a resource in a UserControl from a DataTemplateSelector class in WPF?

asking the same.

BUT... I am not satisfied with th

1条回答
  •  被撕碎了的回忆
    2021-02-10 00:23

    Yes, you can cast the container parameter to FrameworkElement and call FindResource to do a resource lookup starting at the ContentPresenter. For example:

    Code:

    public class MySelector
        : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate
            (object item, DependencyObject container)
        {
            // Determine the resource key to use
            var key = item.ToString() == "a" ? "one" : "two";
            // Find the resource starting from the container
            return ((FrameworkElement)container).FindResource(key) as DataTemplate;
        }
    }
    

    XAML:

    
        
            
                Template One
            
            
                Template Two
            
            
        
        
            
            
        
    
    

    0 讨论(0)
提交回复
热议问题