【发布时间】:2011-06-06 03:34:26
【问题描述】:
我试图在 ListBoxItem 被选中时切换它的 ContentPresenter,同时使用多个 DataTemplates 来表示不同类型的数据。
这是在里面定义 ListBox 的 UserControl:
<UserControl x:Class="Homage.View.FilePanelView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vw="clr-namespace:Homage.View"
xmlns:vm="clr-namespace:Homage.ViewModel"
xmlns:ctrl="clr-namespace:Homage.Controls"
mc:Ignorable="d">
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:SlugViewModel}">
<vw:SlugView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:HeaderSlugViewModel}">
<vw:HeaderSlugView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:ContentSlugViewModel}">
<vw:ContentSlugView />
</DataTemplate>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Name="SlugContainer" Background="Transparent" BorderBrush="Black" BorderThickness="1" CornerRadius="2" Margin="0,5,0,0" Padding="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Content="{Binding DisplayName}" />
<ContentPresenter Grid.Row="1" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="SlugContainer" Property="BorderThickness" Value="5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid>
<ListBox ItemsSource="{Binding Slugs}" Padding="5" />
</Grid>
</UserControl>
根据要显示的数据类型(例如,“Header Slug”),将某个 DataTemplate 应用于 ListBoxItem。这很好用,但我想根据显示的数据类型将所选 ListBoxItem 的 DataTemplate 调整为不同的 DataTemplate。
我们的目标是,由于每种数据类型都不同,因此每种数据类型在未选中时都具有独特的外观,并且在选中时会收到一组独特的选项。
如果我能实现上述工作,那就太好了!但是,我也想把事情复杂化……
虽然每种数据类型都有独特的控件,但它们也有共同的控件。因此,理想情况下,我希望将所有常用控件定义一次,以便它们出现在 ListBox 中的同一位置。
<DataTemplate x:Key="CommonSelectedTemplate">
<!-- common controls -->
...
<DataTemplate x:Key="UniqueSelectedTemplate">
<!-- all the unique controls -->
<ContentPresenter />
</DataTemplate>
<!-- more common controls -->
...
</DataTemplate>
如果我必须多次(现在)定义所有常见的东西,我会活下去。 =)
感谢您的帮助!
【问题讨论】:
-
This answer 可能会帮助您解决第二个问题。
-
感谢 H.B. 的指点。我目前的设置实际上让我有一个“共同”和“独特”的部分,但我试图让它继续适用于第一个问题的解决方案。我已经看到了一些基于 IsSelected 设置外观的示例,但到目前为止似乎还没有提供常见和独特元素的嵌套结构。
-
您可以使用 DataTemplateSelector 类。但在这种情况下,您应该将 IsSelected 属性添加到每个项目类,并将键添加到所有隐式数据模板。关于常用控件,可以用 UserControl 代替。
标签: wpf listbox controltemplate listboxitem