Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF List of Different Types of User Controls

I have a WPF listbox that houses a user control called JUC.

This works great and as I'm very new to WPF this already is very impressive. What I would like to do now is have different user controls in the list based upon a bound property.

Is this possible? If not, how else should I achieve this?

I'm using a list because I want to allow drop/drag ordering of the user controls, and there will be a variable number so seems to make sense - alternative approaches are welcome.

<ListBox x:Name="peopleListBox" 
    HorizontalAlignment="Stretch" 
    VerticalAlignment="Stretch"
    ItemContainerStyle="{StaticResource ListBoxItemStretch}"
    Foreground="Transparent" 
    BorderBrush="Transparent" 
    Background="Transparent" 
    Grid.ColumnSpan="2" SelectionChanged="peopleListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                     <my:JUC Margin="4"></my:JUC>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
like image 459
Jonno Avatar asked Oct 24 '11 15:10

Jonno


1 Answers

You can use DataTemplateSelector, in SelectTemplate() method you can check which DataTemplate to use for currently passed in item:

In XAML:

<!-- define templates in resources
     ChartDataTemplate is a ChartDataTemplate.xaml, the same for other
-->
<UserControl.Resources>
     <DataTemplate x:Key="ChartDataTemplate">
          <views:LineChartView />
     </DataTemplate>

     <DataTemplate x:Key="GridDataTemplate">
         <views:PieChartView />
     </DataTemplate>
</UserControl.Resources>

<!-- ListView Itemtemplate should point to template selector -->
<ItemsControl.ItemTemplate>     
  <DataTemplate>
      <ContentPresenter 
             ContentTemplateSelector = "{StaticResource MyTemplateSelector}">

In Code behind:

 private sealed class MyTemplateSelector: DataTemplateSelector
 { 

    public override DataTemplate SelectTemplate(
                                      object item, 
                                      DependencyObject container)
    {
        // 1. case item to your object which is bound to each ListView item
        // 2. based on object type/state return correct DataTemplate
        // as this.Resources["ChartDataTemplate"] or
        // this.Resources["GridDataTemplate"] 
    }
  }
like image 164
sll Avatar answered Nov 19 '22 07:11

sll