【问题标题】:WPF: Dynamically change ListBox's ItemTemplate based on ListBox Items SizeWPF:根据 ListBox 项大小动态更改 ListBox 的 ItemTemplate
【发布时间】:2011-03-24 11:47:34
【问题描述】:

我需要根据 ListBox 项目数更改我的 ListBox 的 DataTemplate。我想出了以下 XAML:

<Window.Resources>
  <DataTemplate x:Key="DefaultTemplate">
    <StackPanel Orientation="Horizontal">
   <TextBlock Text="{Binding Path=Text}"/>
   <TextBlock Text="default template" />
    </StackPanel>
  </DataTemplate>
  <DataTemplate x:Key="OtherTemplate">
    <StackPanel Orientation="Horizontal">
   <TextBlock Text="{Binding Path=Text}"/>
   <TextBlock Text="other template" />
    </StackPanel>
  </DataTemplate>      
</Window.Resources>
<ListBox Name="listBox1" ItemsSource="{Binding Path=Items}">
  <ListBox.Style>
    <Style TargetType="{x:Type ListBox}">
      <Setter Property="ItemTemplate" Value="{StaticResource DefaultTemplate}" />
        <Style.Triggers>
          <DataTrigger Binding="{Binding Path=Items.Count}" Value="1">
             <Setter Property="ItemTemplate" Value="{StaticResource OtherTemplate}"/>
          </DataTrigger>
        </Style.Triggers>
     </Style>
  </ListBox.Style>     
</ListBox>

使用上面的 XAML,一旦我将两个或更多项目添加到绑定列表中,数据模板就会按预期更改(从其他更改为默认)。但是,如果我删除列表中包含两个以上项目的第一项,则整个列表框将变为空(我验证了绑定列表是非空的)。删除两个项目列表中的第二个项目可以正常工作(即模板从默认更改为其他)。

任何想法为什么会发生这种情况?还是我解决这个问题的方法不对?

【问题讨论】:

    标签: wpf listbox datatemplate listboxitem


    【解决方案1】:

    您可以使用数据触发器,也可以使用DataTemplateSelector Here 是一篇介绍基础知识的文章。 here 是将其应用于项目控件(也是列表框)的 MSDN

    【讨论】:

      【解决方案2】:

      我不能说出确切的问题或原因,但这是因为当计数为 1 且只有 1 时,DataTrigger 正在设置模板。

      你可以做 3 件事中的 1 件事来解决这个问题,但我只推荐 1 件事。

      a) 通过从 System.Windows.TriggerBase 派生来实现您自己的 DataTrigger

      b) 使用 System.Windows.Data.IValueConverter 的实现,它将从 ItemsControl.Items.Count 转换为 DataTemplate。通过将一个元素作为 Binding.ConverterParameter 放置在您的资源范围内,将它们转换为 FrameWorkElement 并调用 FrameWorkElement.FindResource() 来检索模板。

      C) 这是我的建议,写你自己的DataTemplateSelector 来完成繁重的工作。此机制专门针对您实现的功能。我最近写了一个,它将根据源对象的类型选择一个 DataTemplate,而不需要一个没有 x:Key 集的 DataTemplate。使用模板选择器上的属性,您可以使用 XAML 将 DataTemplates 传递到 DataTemplateSelector,删除 FindResource 代码“待办事项”列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-09
        • 2014-08-16
        • 1970-01-01
        • 2021-10-18
        • 2013-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多