我有一个ListBox绑定到一个ObservableCollection,它的ItemTemplate包含另一个ListBox。首先,我尝试以这种方式从我的MainWindowViewModel中获取所有列表框(父列表框和内部列表框)中最后选中的项:
public object SelectedItem
{
get { return this.selectedItem; }
set
{
this.selectedItem = value;
base.NotifyPropertyChanged("SelectedItem");
}
}因此,例如,在父ListBox的项目的DataTemplate中,我得到了以下内容:
<ListBox ItemsSource="{Binding Tails}"
SelectedItem="{Binding Path=DataContext.SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>现在的问题是,当我从父listbox中选择一个项目,然后从一个子列表框中选择一个项目时,我会得到这样的结果:
http://i40.tinypic.com/j7bvig.jpg
如您所见,同时选择了两个项目。我该如何解决这个问题呢?
提前谢谢。
发布于 2010-03-12 20:53:52
我已经通过为ListBox控件的SelectedEvent注册一个ClassHandler解决了这个问题。
我刚刚在我的MainWindow类的构造函数中添加了以下内容:
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能够停止这些事件。
https://stackoverflow.com/questions/2413444
复制相似问题