我知道有这个帖子: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?
答案 0 :(得分: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;
}
}
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>