如何在 C# 中为自定义 DataTemplateSelector 获取 DataTemplate 的 {x:DataType} [英] How to get {x:DataType} for a DataTemplate in C# for custom DataTemplateSelector

查看:22
本文介绍了如何在 C# 中为自定义 DataTemplateSelector 获取 DataTemplate 的 {x:DataType}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 ComboBox 控件编写一个自定义的 DataTemplateSelector,我需要用它来为不同种类显示不同的 DateTemplates对象,在 ComboBox 的关闭和打开模式下.

I'm writing a custom DataTemplateSelector for a ComboBox control and I'll need to use it to display different DateTemplates for different kind of objects, in both the closed and open modes for the ComboBox.

这是我想出的 DataTemplateSelector:

public class ComboBoxTypedDataTemplateSelector : DataTemplateSelector
{
    public IEnumerable<DataTemplate> SelectedTemplates { get; set; }

    public IEnumerable<DataTemplate> DropDownTemplates { get; set; }

    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
    {
        IEnumerable<DataTemplate> source = container.FindParent<ComboBoxItem>() == null
            ? SelectedTemplates // Get the template for the closed mode
            : DropDownTemplates; // Get the template for the open UI mode
        Type type = item.GetType();
        return null; // Some LINQ to get the first DataTemplate in source with the {x:DataType} that equals type
    }
}

public sealed class DataTemplatesCollection : List<DataTemplate> { }

这是我在 XAML 中使用它的方式:

And here's how I'd use it in XAML:

<ComboBox>
    <mvvm:ComboBoxTypedDataTemplateSelector>
        <mvvm:ComboBoxTypedDataTemplateSelector.SelectedTemplates>
            <mvvm:DataTemplatesCollection>
                <DataTemplate x:DataType="models:SomeType">
                    <TextBlock Text="{x:Bind ...}"/>
                </DataTemplate>
                <DataTemplate x:DataType="models:SomeOtherType">
                    <TextBlock Text="{x:Bind ...}"/>
                </DataTemplate>
            </mvvm:DataTemplatesCollection>
        </mvvm:ComboBoxTypedDataTemplateSelector.SelectedTemplates>
        <mvvm:ComboBoxTypedDataTemplateSelector.DropDownTemplates>
            <mvvm:DataTemplatesCollection>
                <DataTemplate x:DataType="models:SomeType">
                    <TextBlock Text="{x:Bind ...}"/>
                </DataTemplate>
                <DataTemplate x:DataType="models:SomeOtherType">
                    <TextBlock Text="{x:Bind ...}"/>
                </DataTemplate>
            </mvvm:DataTemplatesCollection>
        </mvvm:ComboBoxTypedDataTemplateSelector.DropDownTemplates>
    </mvvm:ComboBoxTypedDataTemplateSelector>
</ComboBox>

现在,我唯一缺少的拼图是,我不知道如何在 C# 中获得 {x:DataType} 属性(我知道它实际上不是一个真正的属性,但我希望有一种方法通过代码检索它).我需要类似的东西才能从正确的模板组中为每个对象获取正确的 DataTemplate.有什么方法可以实现吗?

Now, the only piece of the puzzle I'm missing, I can't figure out how to get that {x:DataType} property in C# (I know it's not actually a real property, but I hope there's a way to retrieve it via code). I need something like that to be able to get the right DataTemplate for each object, from the right templates group. Is there a way I can achieve that?

注意:我知道我可以只编写一个特定的 DataTemplateSelector,它具有要为每个项目类型返回的模板的硬编码名称,我可以使用该方法作为后备选项.但是,我想知道是否可以用这种方法编写一个更通用的选择器,以使其更加模块化并能够在未来重用它.

NOTE: I know I could just write a specific DataTemplateSelector that has the hardcoded names of the templates to return for each item type, and I can use that method as a fallback option. But, I was wondering if it was possible to write a more generic selector with this approach in order to make it more modular and be able to reuse it in the future.

感谢您的帮助!

EDIT:按照 Vincent 的建议,我编写了一个附加属性来将给定的 Type 存储在 DataTemplate 中:

EDIT: following the suggestion by Vincent, I wrote an attached property to store a given Type in a DataTemplate:

public class DataTypeHelper
{
    public static Type GetAttachedDataType(DataTemplate element)
    {
        return (Type)element.GetValue(AttachedDataTypeProperty);
    }

    public static void SetAttachedDataType(DataTemplate element, Type value)
    {
        element.SetValue(AttachedDataTypeProperty, value);
    }

    public static readonly DependencyProperty AttachedDataTypeProperty =
        DependencyProperty.RegisterAttached("AttachedDataType", typeof(Type), typeof(DataTypeHelper), new PropertyMetadata(default(Type)));
}

我试过这样使用它:

...
 <DataTemplate x:DataType="someXlmns:SomeClass"
               mvvm:DataTypeHelper.AttachedDataType="someXlmns:SomeClass">
     ...
 </DataTemplate>

但是我在将附加属性设置为我的类型的那一行收到了一个 XamlParseException.我尝试将该属性设置为Grid"(作为测试)并且它不会崩溃,我不明白为什么它不能与我的自定义类型一起使用.

But I'm getting a XamlParseException at the line where I set the attached property to my type. I've tried to set that property to "Grid" (just as a test) and it doesn't crash, I don't understand why isn't it working with my custom type.

EDIT #2:看起来 x:Type 标记扩展在 UWP 中不可用,我找不到另一种方法(我认为根本不可能)来获取类型直接来自 XAML 的实例,所以我只需要在 XAML 中使用类型名称,然后将其与模板选择器中的 item.GetType().Name 进行比较.

EDIT #2: looks like the x:Type markup extension is not available in UWP and I couldn't find another way (I don't think it's possible at all) to get a Type instance directly from XAML, so I had to just use the type name in XAML and then compare it to item.GetType().Name in the template selector.

直接从 XAML 分配 Type 属性的能力会更好,因为它还可以在 XAML 设计器中进行语法/拼写检查,但至少这种方法可以正常工作.

The ability to assign a Type property directly from XAML would have been better as it'd also would have had syntax/spell-check in the XAML designer, but at least this approach works fine.

推荐答案

您无法检索此值.这只是提示编译器允许它为绑定生成适当的代码.

You cannot retrieve this value. This is just a hint for the compiler to allow it to generate the appropriate code for the binding.

您可以创建自定义附加属性来存储您需要的内容,也可以使用 Name 属性.

You can either create a custom attached property to store what you need or use the Name property.

<local:Selector x:Key="selector" >
    <local:Selector.Template1>
        <DataTemplate x:DataType="local:Item" x:Name="template1" >
            <.../>
        </DataTemplate>
    </local:Selector.Template1>
</local:Selector>

然后在选择器实现中

Template1.GetValue(FrameworkElement.NameProperty);

这篇关于如何在 C# 中为自定义 DataTemplateSelector 获取 DataTemplate 的 {x:DataType}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆