我正在创建自己的UserControl,而且在我的XAML中,在UserControl.Resources部分下有两个不同的DataTemplates。我想根据列表视图中显示的对象的属性值选择这两个数据模板之一。我通过创建自定义DataTemplateSelector类并重写SelectTemplate方法来实现此目的,该方法应返回我希望使用的DataTemplate。然而,我不知道如何“找到”位于UserControls资源部分中的datatemplates,我看到的所有示例都只从Window.Resources中获取datatemplates。在这个示例中,他们获取当前的MainWindow,然后使用FindResource查找DataTemplate,那么我该如何以类似的方式获取我的UserControl呢?
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
if (item != null && item is AuctionItem)
{
AuctionItem auctionItem = item as AuctionItem;
Window window = Application.Current.MainWindow;
switch (auctionItem.SpecialFeatures)
{
case SpecialFeatures.None:
return
window.FindResource("AuctionItem_None")
as DataTemplate;
case SpecialFeatures.Color:
return
window.FindResource("AuctionItem_Color")
as DataTemplate;
}
}
return null;
}
上面的示例来自于这里:ItemsControl.ItemTemplateSelector 属性