首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不同类型的用户控件的WPF列表

不同类型的用户控件的WPF列表
EN

Stack Overflow用户
提问于 2011-10-24 23:00:14
回答 1查看 1.5K关注 0票数 5

我有一个WPF列表框,其中包含一个名为JUC的用户控件。

这很好用,因为我是WPF的新手,这已经给我留下了深刻的印象。我现在想做的是根据绑定的属性在列表中拥有不同的用户控件。

这个是可能的吗?如果没有,我还应该如何实现这一点?

我使用列表是因为我想要允许用户控件的拖放排序,并且会有一个可变的数字,所以看起来很有意义--欢迎其他方法。

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-24 23:03:24

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

在XAML中:

代码语言:javascript
复制
<!-- 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}">

在Code Code中:

代码语言:javascript
复制
 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"] 
    }
  }
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7877645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档