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

5
我知道有这个线程:在WPF中,如何从DataTemplateSelector类中查找UserControl中的资源? 虽然提出了同样的问题。但是……我对答案不满意!一定有一种方法可以获取包含ContentControl/Presenter的UserControl的资源:
ContentTemplateSelector="{StaticResource MySelector}" 

每个派生的DataTemplateSelector类在其SelectedTemplate方法中都有一个参数 => 容器,该容器类型为DependencyObject。
在我的情况下,容器是contentcontrol。
是否可能从“contentcontrol”开始向上遍历可视树,并尝试通过FindAncestor获取UserControl?
1个回答

13

是的,您可以将 container 参数转换为 FrameworkElement 并调用 FindResourceContentPresenter 开始进行资源查找。例如:

代码:

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>

1
工作了!!!我也把你的解决方案放在另一个有糟糕解决方案的线程中,这样也许你会得到更多分数;-) - Elisabeth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接