【发布时间】:2021-07-03 13:17:23
【问题描述】:
我这里有一个ListBox,它会显示一些被选中的项目。
<ListBox IsEnabled="False" x:Name="SecondaryModelSelector" SelectionMode="Extended" SelectedItem="{Binding Path=DataContext.SelectedSecondaryModels, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}, Mode=OneWay}" ItemsSource="{Binding Path=DataContext.AvailableModels, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Name}" Margin="5,0,5,0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
所选项目设置在ComboBox 中,因此ListBox 被禁用,Mode=OneWay 禁用ListBox 本身中的选择。
模板如下所示:
<Style x:Key="MyListBoxItem" TargetType="ListBoxItem">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="Border" Padding="2">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background" Value="Blue"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="MyListBoxBorder" TargetType="{x:Type ListBox}">
<Setter Property="ItemContainerStyle" Value="{StaticResource MyListBoxItem}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<Border x:Name="OuterBorder">
<ScrollViewer Margin="0" Focusable="false">
<StackPanel Margin="2" IsItemsHost="True" />
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
现在的问题是,我无法显示多个选定的项目,即背景不会变成蓝色。只显示一个选定的项目是没有问题的。
有效(但只显示一个选定的项目...)
public Cpu SelectedSecondaryModels
{
get { return SelectedGlobalVariable.SecondaryModels.FirstOrDefault(); }
}
不起作用:
public ObservableCollection<Model> SelectedSecondaryModels
{
get { return new ObservableCollection<Model>(SelectedGlobalVariable.SecondaryModels); }
}
我没有错误,那么如何显示多个选定的项目?
我尝试了SelectedItems 而不是SelectedItem,但这是只读字段。
当我允许选择 ListBox 中的项目时,会出现蓝色背景,并且由于没有 setter 方法,绑定会引发错误。
【问题讨论】: