在两个列表框之间同步(多重)选择
本文关键字:同步 之间 多重 选择 两个 列表 | 更新日期: 2023-09-27 18:29:15
我有两个列表框,它们绑定到同一数据源(文件名数组)。一个列表框将文件视为图标,而另一个则将其视为列表。现在我希望他们有相同的选择。因此,当我在一个文件中多重选择两个或多个文件时,同样的文件也应该在另一个中选择。有没有办法做到这一点,最好是在XAML中?我尝试了IsSynchronizedWithCurrentItem
和绑定到SelectedItem
,但这些仅适用于单选项。
<Listbox Name="listView" ItemsSource="{Binding Files}">
<Listbox.ItemTemplate>
// View as list
</Listbox.ItemTemplate>
</ListBox>
<Listbox Name="IconView" ItemsSource="{Binding Files}">
<Listbox.ItemTemplate>
// View as Icon grid
</Listbox.ItemTemplate>
</ListBox>
试试这个代码
XAML
<StackPanel>
<ListBox Height="100" SelectionMode="Multiple" SelectedItem="{Binding SelectedListItem}" x:Name="listview" ItemsSource="{Binding ListBoxItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Item}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<ListBox Height="100" x:Name="itemview" SelectionMode="Multiple" SelectedItem="{Binding SelectedListItem}" ItemsSource="{Binding ListBoxItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Item}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</StackPanel>
ViewModel
private ObservableCollection<MultipleSelection> listBoxItems = new ObservableCollection<MultipleSelection>();
public ObservableCollection<MultipleSelection> ListBoxItems
{
get
{
return listBoxItems;
}
set
{
listBoxItems = value;
this.RaisePropertyChanged("ListBoxItems");
}
}
private MultipleSelection selectedListItem;
public MultipleSelection SelectedListItem
{
get
{
return selectedListItem;
}
set
{
selectedListItem = value;
var selectedItems = ListBoxItems.Where(x => x.IsSelected);
this.RaisePropertyChanged("SelectedListItem");
}
}
public class MultipleSelection : INotifyPropertyChanged
{
private string item;
public string Item
{
get { return item; }
set
{
item = value;
this.RaisePropertyChanged("Item");
}
}
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
this.RaisePropertyChanged("IsSelected");
}
}
}