WPF:从 DataTemplateSelector 类中的 UserControl 中查找资源 [英] WPF: Find Resources from UserControl within DataTemplateSelector class
问题描述
我知道有这个线程:如何从 WPF 中的 DataTemplateSelector 类中查找 UserControl 中的资源?
同样的问题.
但是……我对答案不满意!一定有办法获取
BUT... I am not satisfied with the answer! THERE MUST be a way to grab the Resources of the
包含声明此内容的 ContentControl/Presenter 的 UserControl:
UserControl containing the ContentControl/Presenter declaring this:
ContentTemplateSelector="{StaticResource MySelector}"
每个派生的 DataTemplateSelector
类在其 SelectedTemplate
方法中的一个参数 =>
Each derived DataTemplateSelector
class a parameter in its SelectedTemplate
Method =>
类型为 DependencyObject 的容器.
container which is typeof DependencyObject.
就我而言,容器是内容控件.
Well container is in my case the contentcontrol.
是否不可能从contentcontrol"开始爬上可视化树并尝试通过 FindAncestor 获取 UserControl ?
推荐答案
是的,您可以将 container
参数强制转换为 FrameworkElement
并调用 FindResource 从 ContentPresenter
.例如:
Yes, you can cast the container
parameter to FrameworkElement
and call FindResource to do a resource lookup starting at the ContentPresenter
. For example:
代码:
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 中查找资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!