在列表框中使用SelectionChanged取消选择项目时遇到问题

时间:2013-04-05 09:51:54

标签: c# wpf listbox selection

我有两个ListBox彼此相邻。在XAML文件中,它看起来像这样:

<ListBox Name="first_box" ItemsSource="{Binding Path=Firstlist}"  
    DisplayMemberPath="name" SelectionMode="Single" 
    SelectionChanged="Firstlist_SelectionChanged"/>
<ListBox Name="second_box" ItemsSource="{Binding Path=SecondList}"  
    DisplayMemberPath="name" SelectionMode="Single" 
    SelectionChanged="Secondlist_SelectionChanged"/>

我要做的是当选择其中一个ListBox中的项目时,另一个ListBox应该丢失它的选择。但我认为丢失该选择会再次触发SelectionChanged,从而删除其他ListBox中的选择,因此转发......

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

一种解决方案是测试所选项是否为空:

Firstlist_SelectionChanged(object o, EventArgs e)
{
    if(first_box.SelectedItem != null)
    {
        second_box.SelectedItem = null;
    }
}

Secondlist_SelectionChanged(object o, EventArgs e)
{
    if(second_box.SelectedItem != null)
    {
        first_box.SelectedItem = null;
    }
}

初步情况:

Box1 => Item1
Box2 => null

点击Box2中的项目

Box1 => Item1
Box2 => Item2 => Event fire

Box2是否为空?不,所以将Box1设置为null

Box1 => null => Event fire
Box2 => Item2

Box1是否为空?是的,没有行动。
最终情况:

Box1 => null
Box2 => Item2