我有一个ListBox
,我使用以下XAML样式设置了项目的样式:
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Height" Value="120px" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="MenuButtonBorder" Background="Transparent"
BorderBrush="{StaticResource PrimaryColor}" BorderThickness="0,0,0,1">
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<Path x:Name="MenuButtonIcon" Data="{Binding IconPathString}" Margin="0,0,0,20"
StrokeThickness="1" Stroke="{StaticResource PrimaryColor}"
Fill="{StaticResource PrimaryColor}" HorizontalAlignment="Center" />
<TextBlock x:Name="MenuButtonLabel" Text="{Binding Label}"
FontSize="{StaticResource Title1FontSize}"
Foreground="{StaticResource PrimaryColor}" HorizontalAlignment="Center" />
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="MenuButtonBorder" Property="Background" Value="{StaticResource PrimaryColor}" />
<Setter TargetName="MenuButtonLabel" Property="Foreground" Value="{StaticResource HighlightColor}" />
<Setter TargetName="MenuButtonIcon" Property="Fill" Value="{StaticResource HighlightColor}" />
<Setter TargetName="MenuButtonIcon" Property="Stroke" Value="{StaticResource HighlightColor}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
ListBox
ItemsSource
绑定到viewmodel中的ObservableCollection
属性。在其中一个由MenuButtonLabel
值标识的项目中,我想要一个不同的模板,我在其中添加了几个控件。怎么办呢?
答案 0 :(得分:3)
您可以使用DataTemplateSelector。将它指定为ListBox
的ItemTemplateSelector<强> XAML 强>
<ListBox ItemsSource="{Binding Items}" ItemTemplateSelector="{StaticResource myTemplateSelector}" />
<强> DataTemplateSelector 强>
class MyTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
// TODO: cast item to your viewmodel
// return template based on the Label property;
}
}
注意:您可以在DataTemplateSelector上为不同的DataTemplates创建属性,也可以从容器中获取模板
FrameworkElement element = container as FrameworkElement;
return element.FindResource("mycoolTemplate") as DataTemplate;