2012-07-16 62 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