通过ListBoxItem将ObservableCollection绑定到ListBox

时间:2018-07-12 10:28:43

标签: c# wpf listbox observablecollection listboxitem

我正在尝试将ObservableCollection与ListBox结合使用,以便在将元素添加到ObservableCollection时像这样自动地更新ListBox;

panels = new ObservableCollection<PanelCanvas>();
PanelList.DisplayMemberPath = "Name";
PanelList.ItemsSource = panels;

这工作得很好,但是我确实有一个我真正需要的ListBoxItem.Selected事件,现在我无法使用它,因为我的ListBox现在填充了PanelCanvas对象而不是ListBoxItem对象。

因此,我有两种方法-将ObservableCollection附加到ListBox,当从面板中删除某项时,它使我可以自动从ListBox中添加/删除事件,以及通过创建新的ListBoxItem对象和将它们放到ListBox中。这种方法意味着我可以使用ListBoxItem.Selected事件!

我真正想要的是一种将两者结合的方法-因此,ListBox由ObservableCollection自动填充,而不是用PanelCanvas对象填充ListBox,而是使用ListBoxItem对象填充。这可能吗?

编辑:我进行了一些挖掘,发现可以使用ListBox的SelectionChanged事件和SelectedItem属性使我获得令人满意的相似行为。我仍然非常感谢其他回应!

1 个答案:

答案 0 :(得分:0)

您可以通过编程方式为ListBoxItem.SelectedEvent事件添加事件处理程序,如下所示:

panels = new ObservableCollection<PanelCanvas>();
PanelList.DisplayMemberPath = "Name";
PanelList.ItemsSource = panels;
PanelList.AddHandler(ListBoxItem.SelectedEvent, new RoutedEventHandler(ListBox_Selected), true);

...其中ListBox_Selected是您的事件处理程序:

private void ListBox_Selected(object sender, RoutedEventArgs e)
{
    ListBoxItem item = e.OriginalSource as ListBoxItem;
    PanelCanvas panelCanvas = item.DataContext as PanelCanvas;
    //...
}

或者您可以将SelectedItem的{​​{1}}属性绑定到视图模型的ListBox对象(如果有)。

或处理PanelCanvas事件。