如何在某些 ListBox 项目上使用不同的控件模板?

How to use a different controltemplate on certain ListBox items?

我有一个 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 绑定到视图模型中的 ObservableCollection 属性。在其中一个由 MenuButtonLabel 值标识的项目中,我想要一个不同的模板,我在其中添加了几个控件。如何做到这一点?

您可以使用 DataTemplateSelector。将其指定为您的 ItemTemplateSelector ListBox

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;