WPF: finding resources from UserControl in the DataTemplateSelector class

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

asking the same thing.

BUT ... I am not satisfied with the answer! There MUST be a way to grab resources

A UserControl containing a ContentControl / Presenter declaring this:

ContentTemplateSelector="{StaticResource MySelector}" 

Each derived class DataTemplateSelector contains a parameter in its SelectedTemplate Method =>

which is typeof DependencyObject.

The container box in my case contains content.

It would be impossible to climb the visual tree, starting with the "contentcontrol" and try to get the UserControl through FindAncestor?

+4
source share
1 answer

Yes, you can apply the container parameter to FrameworkElement and call FindResource to search for resources starting with ContentPresenter . For instance:

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:

 <UserControl x:Class="WpfApplication1.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" > <UserControl.Resources> <DataTemplate x:Key="one"> <TextBlock>Template One</TextBlock> </DataTemplate> <DataTemplate x:Key="two"> <TextBlock>Template Two</TextBlock> </DataTemplate> <local:MySelector x:Key="MySelector"/> </UserControl.Resources> <StackPanel> <ContentPresenter ContentTemplateSelector="{StaticResource MySelector}" Content="a"/> <ContentPresenter ContentTemplateSelector="{StaticResource MySelector}" Content="b"/> </StackPanel> </UserControl> 
+10
source

Source: https://habr.com/ru/post/1332148/


All Articles