WPF ListBox多选绑定

时间:2011-01-17 21:09:48

标签: c# wpf xaml

我左边有两个listBox,右边有一个listBox。当我在左侧列表框中选择“contactList”项时,“label”信息应显示在右侧列表框中,此部分工作正常。我遇到的问题是多选,因为目前它只显示一个选择的信息。我将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;

                }

            }
        }
    }

2 个答案:

答案 0 :(得分:3)

我认为每个人都对此部分感到困惑

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上设置项目源,您已经将其绑定到集合,并且您只需要替换此方法中的内容。 (只有一个调用清除顶部的集合,并且没有调用设置ItemsSource,因为它已经被绑定了)

答案 1 :(得分:1)

我根本无法获得你在那里所做的所有代码,但你通常如何处理你所描述的场景是通过将第二个ListBox直接绑定到第一个,应该看起来像这样: / p>

<ListBox Name="ListBox1" ItemsSouce="{Binding SomeOriginalSource}" .../>
<ListBox ItemsSouce="{Binding ElementName=ListBox1, Path=SelectedItems}".../>

编辑:然后您可以使用枚举内部集合的DataTemplate(例如,可能导致您拥有包含其他ListBox的ListBox),或者您将绑定器添加到将内部集合合并为单个的绑定中像约翰加德纳那样的集合。

相关问题