Create a generic list in xaml 4.5+

╄→尐↘猪︶ㄣ 提交于 2020-04-13 17:17:15

问题


I am trying to make a rule list for one of my usercontrols. List contains a custom type List<StringInputRule>. I am using DependancyProperty to databind.

I am trying to set the rules in xaml for the control as such:

<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# code for dependancy property for the control:

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>()));
}

So the following approach does not pass any values, yet it compiles. I have read that generic types could be initialized within xaml from 2009 version with 4.0, yet I could have not located an example.

My question: How to define generic List in xaml?

Edit: As to this day there is no solid solution to the problem.

WorkAround (as pointed by Szabolcs Dézsi): how use List<T> within xaml?


回答1:


It would look like this:

<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 is a XAML 2009 feature. Unfortunately it's not supported in compiled XAML, so you won't be able to use it in your WPF application. Read more here, here and here.



来源:https://stackoverflow.com/questions/35183412/create-a-generic-list-in-xaml-4-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!