【问题标题】:SelectionChanged of a child ListBox子列表框的 SelectionChanged
【发布时间】:2010-03-09 23:33:54
【问题描述】:

我有一个 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}}}"/>

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

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

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

提前致谢。

【问题讨论】:

    标签: wpf listbox datatemplate selecteditem


    【解决方案1】:

    我已经通过为 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 能够停止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多