Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a generic list in xaml 4.5+

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?

like image 844
Karolis Kajenas Avatar asked Nov 27 '25 04:11

Karolis Kajenas


1 Answers

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.

like image 156
Szabolcs Dézsi Avatar answered Nov 28 '25 18:11

Szabolcs Dézsi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!