WPF不同类型用户控件列表

5
我有一个WPF列表框,其中包含一个名为JUC的用户控件。
这非常好用,因为我很新于WPF,这已经非常令人印象深刻了。现在我想根据绑定属性在列表中放置不同的用户控件。
这是否可能?如果不是,我该如何实现呢?
我使用列表是因为我希望允许拖放排序的用户控件,并且数量是可变的,所以似乎是有意义的 - 欢迎提出其他方法。
<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>
1个回答

7

您可以使用DataTemplateSelector,在SelectTemplate() 方法中,您可以检查当前传递的项应该使用哪个DataTemplate:

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}">

在代码后台中:
 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"] 
    }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接