【问题标题】:ListBox display multiple selected itemsListBox 显示多个选中项
【发布时间】: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 方法,绑定会引发错误。

【问题讨论】:

    标签: c# wpf listbox


    【解决方案1】:

    SelectedItem 属性不能绑定到要选择的多个项目的集合。

    正如您已经注意到的,SelectedItems 是一个只读属性。

    您可以使用附加行为来解决此问题。请参阅this blog postthis example 了解有关如何执行此操作的更多信息。

    您还可以在这里找到一些解决方案:

    Bind to SelectedItems from DataGrid or ListBox in MVVM

    【讨论】:

    • 我希望找到更好的解决方案,因为这些链接或多或少已经有几年的历史了。非常令人失望的是没有改善......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多