2010-03-09 43 views
0

我有一个ListBox绑定到一个ObservableCollection ItemTemplate包含另一个ListBox。首先,我想从我的MainWindowViewModel这种方式让所有的列表框的最后一个选择的项目(无论是家长和内部的):SelectionChanged的孩子列表框

public object SelectedItem 
{ 
    get { return this.selectedItem; } 
    set 
    { 
     this.selectedItem = value; 
     base.NotifyPropertyChanged("SelectedItem"); 
    } 
} 

因此,例如,在项目的DataTemplate中父列表框我有这样的:

<ListBox ItemsSource="{Binding Tails}" 
SelectedItem="{Binding Path=DataContext.SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/> 

现在的问题是,当我选择从父ListBox中的项目,然后从孩子列表框中的项目,我得到这个:

http://i40.tinypic.com/j7bvig.jpg

如您所见,同时选择两个项目。我该如何解决这个问题?

在此先感谢。

回答

0

我已经通过为ListBox控件的SelectedEvent注册一个ClassHandler来解决此问题。

我只是在我的主窗口类的构造函数中加入这样的:

EventManager.RegisterClassHandler(typeof(ListBox), 
      ListBox.SelectedEvent, 
      new RoutedEventHandler(this.ListBox_OnSelected)); 

这样,我ListBox_OnSelected事件处理程序将被称为每当一个列表框被调用,控制的事件处理程序之前本身被称为。

在MainWindowViewModel我有一个叫SelectedListBox属性,跟踪其中的一个选择:

public System.Windows.Controls.ListBox SelectedListBox 
{ 
    get { return this.selectedListBox; } 
    set 
    { 
     if (this.selectedListBox != null) 
     { 
      this.selectedListBox.UnselectAll(); 
     } 
     this.selectedListBox = value; 
    } 
} 

为什么不能用一个简单的SelectionChanged事件处理程序?因为在上面的代码中,每当你取消选择一个列表框时,它就会再次引发同一个事件,从而导致WPF能够停止的无限循环。

相关问题