有没有一种方法可以从ListBox以编程方式确定关联的ObservableCollection?从列表框中获取ObservableCollection
我将ItemsSource绑定到我的XAML中的ListBox,并且当用户从中选择一个项目时,我希望程序不仅能够找到该项目来自哪个ListBox(我已经设法完成),而且还要获取与其关联的ObservableCollection。我认为通过使用sourceContainer.ItemsSource.ToString()(其中sourceContainer是以编程方式发现的列表框),我将能够确定它后面的DataBound ObservableCollection。但是,情况并非如此。我错过了什么?
谢谢!
编辑:这里有一些关于创建ObservableCollections的代码,以及我如何确定选择哪个框。 (我知道这可能不是最好的方式,我还在学习...)
首先,在XAML(每个列表框有这一行一般绑定):
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)sender;并得到listbox.ItemsSource获取相关的集合 – Artiom 2012-07-16 15:48:12