2012-07-16 63 views
1

有没有一种方法可以从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? 

如果需要其他东西,请告诉我。

+0

假设你不太明白做什么你需要。如果订阅了已更改的列表框选择,则可以从发件人对象获取列表框。 var listbox =(ListBox)sender;并得到listbox.ItemsSource获取相关的集合 – Artiom 2012-07-16 15:48:12

回答

2

如果你直接绑定到是ObservableCollection<T>的属性,你应该能够做到这一点:

var col = (ObservableCollection<MyClass>)sourceContainer.ItemsSource; 

如果不是的话,你就需要发布相关的XAML和代码。

+0

我试过你的建议,但由于某种原因,它仍然无法正常工作。当这条线被击中时,它只是读“Count = 1”。我希望让它读取集合的实际名称。 如果我说的没有意义,请随时纠正我。数据绑定对我来说还是很陌生的。 – 2012-07-16 15:30:35

+0

这听起来像你正在得到一个列表(ObservableCollection)回来1项?你的名字是什么意思?你应该只关心一个集合的内容,而不是集合的名称......这看起来像一个UI问题,并且可能与你的业务实现耦合,这可能不应该在那里 – 2012-07-16 15:42:54

0

与列表框关联的集合是ObservableCollection? Cuz如果你设置了一个数组 - 它不会在后台将魔术转换为ObservableCollection。

告诉你为什么需要这个逻辑。假设其他逻辑中的错误是错误的。

1

Eren's answer是正确的,您可以通过将ItemsSource属性转换为正确的集合类型来获取实际集合。

ObservableCollection<DataItem> sourceCollection = 
    sourceContainer.ItemsSource as ObservableCollection<DataItem>; 

如果你只是想Name属性为您的评论所说,你可以得到BindingItemsSourceProperty,并期待在Path财产

var binding = soureContainer.GetBindingExpression(ListBox.ItemsSourceProperty); 
var sourceCollectionName = binding.ParentBinding.Path.Path; 
+0

感谢您解决问题;我现在可以看到为什么一个人不会特别关心ObservableCollection的名字,因为它有更多有用的函数名字。我希望我可以将这些设置为最佳答案! – 2012-07-16 17:02:32

+0

@NateFrueh我想知道你想要'Name'属性的地球:) – Rachel 2012-07-16 17:05:32