【问题标题】:Create a generic list in xaml 4.5+在 xaml 4.5+ 中创建通用列表
【发布时间】:2016-02-03 17:10:25
【问题描述】:

我正在尝试为我的一个用户控件创建一个规则列表。 List 包含一个自定义类型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 版本 4.0 的 xaml 中初始化,但我可能找不到示例。

我的问题:如何在 xaml 中定义泛型 List?

编辑:截至目前,该问题还没有可靠的解决方案。

WorkAround(由 Szabolcs Dézsi 指出):how use List<T> within xaml?

【问题讨论】:

    标签: c# wpf xaml generics .net-4.5


    【解决方案1】:

    看起来像这样:

    <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 应用程序中使用它。阅读更多 hereherehere

    【讨论】:

    • 不幸的是,我不能将此标记为答案,因为它只是说明了您不能这样做的事实,但实际上我已经通过添加从 List 继承的其他非泛型类型来解决它和使用子类作为类型。您可以相应地更改您的答案,我会将其标记为答案。祝你有美好的一天!
    • 是的,我知道,这个问题是重复的:stackoverflow.com/a/7152297/4620101 虽然我觉得这是一种解决方法,而不是您特定问题的答案:“如何在 xaml 中定义通用列表? "
    • 最初,正如您在评论中提到的那样,我正在寻找一种更可靠的方法,这就是我写这个问题的原因。显然,您不能没有这种解决方法:) 感谢您的努力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 2022-08-13
    • 1970-01-01
    相关资源
    最近更新 更多