Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This is part of a series on New WPF\XAML Features
XAML 2009 supports generics J .. In previous releases, if you needed to have an observableCollection for databinding you would probably have written code like
class PersonCollection:ObservableCollection<Person>{}
<l:PersonCollection>
<Person Name="Tom" />
</l:PersonCollection>
In this release, you can now write this as
<ObservableCollection x:TypeArguments='local:Person' xmlns='clr-namespace:System.Collections.ObjectModel;assembly=System' >
<local:Person Name='Tom' Age='21' />
</ObservableCollection>
…
<ListBox ItemsSource='{Binding}' DisplayMemberPath='Name'></ListBox>
Notice the use of TypeArguments to specify the collection type (Person in this case). It is used to pass the required constraints for a generic type
Lets go for some more examples. Simple Dictionary with the key\value pair being strings
<StackPanel.DataContext>
<coll:Dictionary x:TypeArguments='x:String, x:String' xmlns:coll='clr-namespace:System.Collections.Generic;assembly=mscorlib'>
<x:String x:Key='One'>1</x:String>
<x:String x:Key='Two'>2</x:String>
</coll:Dictionary>
</StackPanel.DataContext>
<ListBox ItemsSource='{Binding}' DisplayMemberPath='Key' Width='100'></ListBox>
Next we have a slightly more complicated dictionary with an object as the key\value pair. Interesting to note here is that Key
<StackPanel.DataContext>
<coll:Dictionary x:TypeArguments='p:Object, p:Object' xmlns:p='clr-namespace:System;assembly=mscorlib'>
<Point X='42' Y='3' >
<x:Key>
<Point X='100' Y='1' />
</x:Key>
</Point>
<x:Null x:Key='three' />
</coll:Dictionary>
</StackPanel.DataContext>
<ListBox ItemsSource='{Binding}' DisplayMemberPath='Value' Width='100'></ListBox>
And finally a nested dictionary sample
<StackPanel.Resources>
<coll:Dictionary x:TypeArguments='p:Object, coll:Dictionary(p:Object, p:Object)' x:Key='NestedItems'>
<coll:Dictionary x:Key='Dictionary1' x:TypeArguments='x:Object, x:Object'>
<x:String x:Key='One'>1</x:String>
<Point X='42' Y='3'>
<x:Key>
<Point X='11' Y='22' />
</x:Key>
</Point>
</coll:Dictionary>
</coll:Dictionary>
</StackPanel.Resources>
<ListBox ItemsSource='{StaticResource NestedItems}' DisplayMemberPath='Key'></ListBox>
Sample app showing the usage is attached.
Note that XAML 2009 features work only for loose XAML in WPF.
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in