Using Dictionary as Binding source for Xaml Collection

26 בAugust 2015

אין תגובות

If you find the trigger just pull it off..

Unfortunately I have found more than once programmers who used to translate the dictionary struct into an IEnumerable to present one dimension collection at the UI,

And its is not because ObseervableCollection problem since it is quite easy to have an ObservableDictionary if you have the Notification binding consideration.

Assume you have an Dictionary of key value in your model, lets say of CustomerName, and a Customer, while you already have it, and all what yours App is about Customer Names in DropDown List, but in underline you do need the real Entity of Customer per each selecteditem in the presentation layer.

Well, WPF ComboBox for example is made for it

It can easily bind t collection source of <T,T> type and show you the key/value only while user selection action will set the selection as the second part. All you need is to know some simple properties:

ItemsSource : keep it simple like always , and bind it to your Dictionary<T,T> name.

SelectedValue : most of people just used SelectedItem, but here come the big different, the SelectedItem in case of KeyValuePair collection binding will be KeyVluePair item, but selectedValue allow you to decide specific Property from the SelectedItem internals by activate the SelectedValuePath property , meaning which part of the item will be in charge as SelectedValue, so: SelectedValuePath=”Value”

To complete the action you must know the next property :

DisplayMemberPath=”Key” which simply tell the UI Control what to show for users in scenario like that.

So as a demo:

So as a demo:

<ComboBox IsSynchronizedWithCurrentItem="True"

               ItemsSource="{Binding VMSource}"

               SelectedValue="{Binding    

               SelectedPreviewTargetPath}"

               DisplayMemberPath="Key" SelectedValuePath="Value" />

Obviously that VMSource is public Property of Type Dictionary<T,T>

This is came up and relevant a specially because of Performance issues, if your DataStruct is

Key-value-Pair and on any selection you activate a service to get the real data you might be in a problem.

Happy codding.

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *