【发布时间】:2012-07-16 15:01:57
【问题描述】:
有没有办法以编程方式从 ListBox 确定关联的 ObservableCollection?
我在我的 XAML 中将 ItemsSource 绑定到 ListBox,当用户从其中选择一个项目时,我希望程序不仅能找到该项目来自哪个 ListBox(我已经设法做到了),而且还能得到与之关联的 ObservableCollection。
我认为通过使用 sourceContainer.ItemsSource.ToString()(其中 sourceContainer 是通过编程找到的 ListBox),我可以确定它背后的 DataBound ObservableCollection。然而,事实并非如此。我错过了什么?
谢谢!
编辑:这里有一些关于创建 ObservableCollections 以及我如何确定选择哪个框的代码。 (我知道这可能不是最好的方法,我还在学习中......)
首先是 XAML(每个 ListBox 都有这一行用于常规绑定):
ItemsSource="{Binding Path=ListOneItems}"
现在是创建 ObservableCollections 的代码:
private ObservableCollection<DataItem> listOneItems;
public ObservableCollection<DataItem> ListOneItems
{
get
{
if (listOneItems == null)
{
listOneItems = new ObservableCollection<DataItem>();
}
return listOneItems;
}
}
程序在此处确定所选项目的父项:
//Finds the name of the container that holds the selected SLBI (similar to finding the initial touched object)
FrameworkElement determineSource = e.OriginalSource as FrameworkElement;
SurfaceListBox sourceContainer = null;
while (sourceContainer == null && determineSource != null)
{
if ((sourceContainer = determineSource as SurfaceListBox) == null)
{
determineSource = VisualTreeHelper.GetParent(determineSource) as FrameworkElement;
}
}
//Name of the parent container
strParentContainer = sourceContainer.Name;
//Name of the ObservableCollection associated with parent container?
如果还需要什么,请告诉我。
【问题讨论】:
-
假设你不太明白你需要什么。如果您订阅的列表框选择发生了变化,您可以从发件人对象中获取列表框。 var listbox=(列表框)发件人;而不是获取 listbox.ItemsSource 以获取关联的集合
标签: c# wpf data-binding listbox observablecollection