WPF:在DataTemplateSelector类中从UserControl查找资源

Eli*_*eth 5 wpf resources user-controls datatemplateselector

我知道有这个线程:如何从WPF中的DataTemplateSelector类中找到UserControl中的资源?

问同样的问题.

但是......我对答案不满意!必须有一种方法来获取资源

包含ContentControl/Presenter的UserControl声明:

ContentTemplateSelector="{StaticResource MySelector}" 
Run Code Online (Sandbox Code Playgroud)

每个派生DataTemplateSelector类在其SelectedTemplateMethod =>中都有一个参数

容器,它是DependencyObject的类型.

好的容器在我的情况下是contentcontrol.

是不是可以从"contentcontrol"开始爬上可视树并尝试通过FindAncestor获取UserControl?

Qua*_*ter 12

是的,您可以将container参数转换为FrameworkElement并调用FindResource以从中开始执行资源查找ContentPresenter.例如:

码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)