2011-01-28 28 views
0

我使用的是同一個窗口,它有兩個作用。在我的窗口內,我有一個listview,我想根據目的綁定到不同的對象。代碼中的綁定問題

其實它只是一個窗口,需要在導入文件。

所以最初我有這個。

<ListView Grid.Row="1" Name="_lvValues" 
    DataContext="{Binding ElementName=_listbox,Path=SelectedItem}" 
    ItemsSource="{Binding Path=DataTable(from selectedItemObject)}"> 

對於其他的目的,我不得不這樣做

<ListView Grid.Row="1" Name="_lvValues" 
    DataContext="{Binding ElementName=ClassName,Path=Object}" 
    ItemsSource="{Binding Path=DataTable(from Object)}"> 

我想這樣做,在if/else語句窗口(構造)的初始化過程中。所以......

if (windowType == Type1) 
    // SetBinding to using listbox 
else 
    // SetBinding to using Object 

我想這個初始化組件後

 binding = new Binding("DataTable"); 
     binding.Source = new Binding("ListBox.SelectedItem"); 
     _lvValues.SetBinding(ListView.ItemsSourceProperty, binding); 

但顯然它沒有工作,我不知道如何着手。

原因,我需要這個,第一個窗口類型有文件,其中第二個窗口類型只有一個文件,所以它不會是正確的,以顯示與只有一個文件列表框的列表。

感謝和問候, 千電子伏

+0

你不能使用每頁都會有一個列表頁面,然後選擇一個文件時,從文件列表頁面切換到詳細列表頁? – Nekresh 2011-01-28 16:34:00

回答

2

如果你的XAML是一個準確的描述你的綁定,你只需要把它轉化爲兩個結果綁定;應該是這樣的對於第一種情況:

Binding contextBinding = new Binding("SelectedItem"); 
contextBinding.Source = _listbox; 
_lvValues.SetBinding(ListView.DataContextProperty, contextBinding); 

Binding itemsBinding = new Binding("DataTable"); 
_lvValues.SetBinding(ListView.ItemsSourceProperty, itemsBinding); 

和第二種情況可能是這樣的:

Binding contextBinding = new Binding("Object"); 
contextBinding.Source = ClassName; 
_lvValues.SetBinding(ListView.DataContextProperty, contextBinding); 

Binding itemsBinding = new Binding("DataTable"); 
_lvValues.SetBinding(ListView.ItemsSourceProperty, itemsBinding); 

(由於ItemsSource時,綁定始終是相同的,只是取決於在DataContext你可以重構它是if子句之外,或在XAML總而言之,我認爲)