【问题标题】:WPF List of Different Types of User Controls不同类型的用户控件的 WPF 列表
【发布时间】:2011-10-24 15:00:13
【问题描述】:

我有一个 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>

【问题讨论】:

    标签: .net wpf list xaml user-controls


    【解决方案1】:

    您可以使用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"] 
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2023-03-11
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      相关资源
      最近更新 更多