我有两个列表框,一个在左边,一个在右边。当我在左侧列表框中选择“联系人列表”项目时,“标签”信息应显示在右侧列表框中,这部分工作正常。我遇到的问题与多选有关,因为目前它只会显示来自一个选择的信息。我将 XAML 中的选择模式更改为多选,但这似乎不起作用。将不胜感激任何帮助。谢谢。
XAML
<Grid x:Name="LayoutRoot" Background="#FFCBD5E6">
<ListBox x:Name="contactsList" SelectionMode="Multiple" Margin="7,8,0,7" ItemsSource="{Binding ContactLists, Mode=Default}" ItemTemplate="{DynamicResource ContactsTemplate}" HorizontalAlignment="Left" Width="254" SelectionChanged="contactsList_SelectionChanged"/>
<ListBox x:Name="tagsList" Margin="293,8,8,8" ItemsSource="{Binding AggLabels, Mode=Default}" ItemTemplate="{StaticResource TagsTemplate}" Style="{StaticResource tagsStyle}" />
</Grid>
代码
private void contactsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (contactsList.SelectedItems.Count > 0)
{
CollectionViewGroup collectionView = contactsList.SelectedItems[0] as CollectionViewGroup;
ContactList selectedContact = contactsList.SelectedItems[0] as ContactList;
ObservableCollection<AggregatedLabel> labelList = new ObservableCollection<AggregatedLabel>();
foreach (ContactList contactList in collectionView.Items)
{
foreach (AggregatedLabel aggLabel in contactList.AggLabels)
{
labelList.Add(aggLabel);
tagsList.ItemsSource = labelList;
}
}
}
}
最佳答案
我想大家对这部分很困惑
CollectionViewGroup collectionView = contactsList.SelectedItems[0] as CollectionViewGroup;
ContactList selectedContact = contactsList.SelectedItems[0] as ContactList;
您只查看了第一个选定的项目。 (SelectedItems[0]
),但将其视为一回事?
你可能需要类似的东西
// only create the list once, outside all the loops
ObservableCollection<AggregatedLabel> labelList = new ObservableCollection<AggregatedLabel>();
foreach (var selected in contactsList.SelectedItems)
{
// pretty much your existing code here, referencing selected instead of SelectedItems[0]
}
// only set the list once, outside all the loops
tagsList.ItemsSource = labelList;
理想情况下,您不会在 tagsList 上设置项目源,您已经将其绑定(bind)到一个集合,并且您只需替换此方法中的内容。 (只需调用一次清除顶部的集合,无需调用设置 ItemsSource,因为它已经被绑定(bind))
关于c# - WPF ListBox 多选绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4717914/