我有一个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
值识别的其中一个项目中,我想拥有一个不同的模板,我添加了几个控件。如何完成?
您可以使用DatateMplatesElector。将其指定为for You listBox
的ItemTemplateSelectorXAML
<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上为不同的数据组件创建属性,也可以从容器中获取模板
FrameworkElement element = container as FrameworkElement;
return element.FindResource("mycoolTemplate") as DataTemplate;