If you want to use your control in xaml, you cannot create a generic UserControl in this way, since WPF just does not support it. How do you declaratively instantiate this type in xaml?
I would see how other controls will handle something like this. For example, a ListBox allows you to populate a list of items without any relation to the type of collection parsed in its ItemsSource.
<ListBox ItemsSource="{Binding DictionaryItems}" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Key}" /> <TextBlock Text="{Binding Value}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
For different types of dictionaries, you can have several DataTemplates for each type of dictionary and switch using TemplateSelector.
public class SomeSelector : DataTemplateSelector { public DataTemplate Template1 { get; set; } public DataTemplate Template2 { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item is IDictionary<string, int>) { return Template1; } return Template2; } }
Then in xaml
<UserControl.Resources> <DataTemplate x:Key="Template1"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Key}" /> <TextBlock Text="{Binding Value}" /> </StackPanel> </DataTemplate> <DataTemplate x:Key="Template2> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Key}" /> <TextBlock Text="{Binding Value}" /> </StackPanel> </DataTemplate> <SomeSelector x:Key="SomeSelector" Template1="{StaticResource Template1}" Template2="{StaticResource Template2}" /> </UserControl.Resources> <ListBox ItemsSource="{Binding DictionaryItems}" ItemTemplateSelector="{StaticResource SomeSelector}" />
James hay
source share