在 xaml 4.5+ 中创建泛型列表
本文关键字:创建 泛型 列表 xaml | 更新日期: 2023-09-27 18:33:14
我正在尝试为我的一个用户控件制作规则列表。列表包含自定义类型 List<StringInputRule>
。我正在使用DependancyProperty
进行数据绑定。
我正在尝试在 xaml 中为控件设置规则:
<controlsDefault:DateEditWithStringInput>
<controlsDefault:DateEditWithStringInput.Rules>
<x:Array Type="controlsDefault:StringInputRule" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<controlsDefault:StringInputRule Key="T" Amount="1" Unit="Day"/>
<controlsDefault:StringInputRule Key="W" Amount="1" Unit="Week"/>
<controlsDefault:StringInputRule Key="M" Amount="1" Unit="Month"/>
</x:Array>
</controlsDefault:DateEditWithStringInput.Rules>
</controlsDefault:DateEditWithStringInput>
控件的依赖项属性的 C# 代码:
public partial class DateEditWithStringInput : UserControl
{
public DateEditWithStringInput()
{
InitializeComponent();
Rules = new List<StringInputRule>();
}
public IList<StringInputRule> Rules
{
get { return (IList<StringInputRule>)GetValue(RulesProperty); }
set { SetValue(RulesProperty, value); }
}
public static readonly DependencyProperty RulesProperty =
DependencyProperty.Register("Rules", typeof(IList<StringInputRule>), typeof(DateEditWithStringInput), new PropertyMetadata(new List<StringInputRule>()));
}
因此,以下方法不传递任何值,但它会进行编译。我已经读到泛型类型可以从 2009 版的 xaml 中使用 4.0 初始化,但我找不到示例。
我的问题:如何在 xaml 中定义泛型列表?
编辑:到目前为止,这个问题没有可靠的解决方案。
解决方法(正如Szabolcs Dézsi所指出的):如何在xaml中使用List
它看起来像这样:
<controlsDefault:DateEditWithStringInput.Rules>
<generic:List x:TypeArguments="controlsDefault:StringInputRule">
<controlsDefault:StringInputRule Key="T" Amount="1" Unit="Day"/>
<controlsDefault:StringInputRule Key="W" Amount="1" Unit="Week"/>
<controlsDefault:StringInputRule Key="M" Amount="1" Unit="Month"/>
</generic:List>
</controlsDefault:DateEditWithStringInput.Rules>
x:TypeArguments
是 XAML 2009 的一项功能。遗憾的是,编译的 XAML 不支持它,因此您将无法在 WPF 应用程序中使用它。在这里、这里和这里阅读更多内容。