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

标签 wpf user-controls resources datatemplateselector

我知道有这个帖子:How to find a resource in a UserControl from a DataTemplateSelector class in WPF?

问同样的问题。

但是...我对答案不满意!一定有办法获取资源

包含 ContentControl/Presenter 的 UserControl 声明如下:

ContentTemplateSelector="{StaticResource MySelector}" 

每个派生的DataTemplateSelector类在其SelectedTemplate方法中都有一个参数=>

容器,其类型为 DependencyObject。

在我的例子中,容器就是内容控件。

是否不可能从“contentcontrol”开始爬上视觉树并尝试 通过 FindAncestor 获取 UserControl ?

最佳答案

是的,您可以将 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>

关于WPF:从 DataTemplateSelector 类中的 UserControl 查找资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4444483/

相关文章:

asp.net - 如何从另一个用户控件继承用户控件?

c# - 将 UserControl 显示为弹出窗口

resources - Dns 服务器 (edns)opt 资源记录类型

c# - 从 WPF 行为向 ViewModel 发送消息

c# - 使用 WPF 控件和 C# 动态生成一个按钮以打开文件对话框并选择一个文件

c# - 构建后消失的用户控件

java - Spring 3.1中如何使用通配符加载xml资源文件

c# - ResX 文件和额外的应用层

wpf - 什么是切换按钮,我们什么时候可以使用它?

c# - InitializeComponent() 有什么作用,它在 WPF 中是如何工作的?