数组或IEnumerable的DataTemplate

本文关键字:DataTemplate IEnumerable 数组 | 更新日期: 2023-09-27 18:25:34

我想创建一个隐式DataTemplate,它可以在我的类的数组或IEnumerable上工作。这样,我就有了一个模板来描述如何渲染一堆项目,而不是一个。我想这样做,这样我就可以在工具提示中显示结果。例如

<TextBlock Text="{Binding Path=CustomerName}" ToolTip="{Binding Path=Invoices}">

工具提示应该看到发票是一堆项目,并使用适当的数据模板。模板看起来像这样:

<DataTemplate DataType="{x:Type Customer[]}">
    <ListBox "ItemsSource={Binding}">
     etc

这不起作用,所以我尝试了这篇文章x:Type和arrays中的例子——怎么做?这涉及创建自定义标记扩展。如果您指定密钥,但不为隐式模板指定密钥,则此操作有效

因此,我尝试制作自己的自定义标记扩展,继承TypeExtension,如下所示,但我收到一个错误,上面写着"字典的键不能是‘System.Windows.Controls.StackPanel’类型。只支持String、TypeExtension和StaticExtension。"这是一个非常奇怪的错误,因为它将数据模板的内容作为键??如果我指定了一个密钥,那么它可以正常工作,但这在很大程度上违背了目的。

[MarkupExtensionReturnType(typeof(Type)), TypeForwardedFrom("PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
public class ArrayTypeExtension
    : TypeExtension
{
    public ArrayTypeExtension() : base() { }
    public ArrayTypeExtension(Type type) : base(type)
    {
    }
    public ArrayTypeExtension(string value) : base(value)
    {
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        Type val = base.ProvideValue(serviceProvider) as Type;
        return val == null ? null : val.MakeArrayType();
    }
}

数组或IEnumerable的DataTemplate

如您链接到{x:Type ns:TypeName[]}的问题中所述,工作。它可能会影响设计者,但在运行时应该是好的。

为了避免设计器错误,可以将模板移动到App.xaml或资源字典(当然,也可以根本不使用设计器)。

(提到模板中的控件的错误听起来像是代码生成器或编译器中的错误,遗憾的是,我怀疑你能对此做些什么。)

如果您可以创建自己的类型,我只是尝试并遵循它,它是有效的。为您的收藏创建一个特定类型:

public class InvoiceCollection : List<Invoice> { }
public class Customer {
    public string name { get; set; }
    InvoiceCollection invoices { get; set; }
}

然后是带有数据模板的XAML:

<DataTemplate DataType={x:Type InvoiceCollection}>
    <ListBox ItemsSource="{Binding}" />
</DataTemplate>
<TextBox Text="{Binding name}" Tooltip="{Binding invoices}" />