2010-01-03 155 views
0

在WPF應用程序我有一個ListViewWPF ListView的數據綁定到的ObservableCollection

<ListView Height="100" Width="434" x:Name="lvItems" ItemsSource="{Binding ElementName=MainWindow, Path=ShowQuCollection}" > 
<ListView.View> 
    <GridView> 
    <GridViewColumn Header="Date" Width="100" DisplayMemberBinding="{Binding Date}"/> 
    <GridViewColumn Header="Time" Width="100" DisplayMemberBinding="{Binding Time}"/> 
    <GridViewColumn Header="Description" Width="200" DisplayMemberBinding="{Binding Description}"/> 
    </GridView> 
</ListView.View> 

其與ObservableCollection通過數據綁定連接:

ObservableCollection<ShowsQu> _ShowQuCollection = 
    new ObservableCollection<ShowsQu>(); 

public ObservableCollection<ShowsQu> ShowQuCollection 
{ get { return _ShowQuCollection; } } 

public class ShowsQu 
{ 
public string ShowCode { get; set; } 
public DateTime Date { get; set; } 
public TimeSpan Time { get; set; } 
public string Description { get; set; } 
} 

ObservableCollection放置在代碼 - 在同一窗口的文件後面,其中ListViewMainWindow。一切正常。

現在我又添加了另一個ListView到不同的窗口,在這種情況下數據綁定不起作用。此數據綁定一塊XAML的我並沒有改變:

ItemsSource="{Binding ElementName=MainWindow, Path=ShowQuCollection} 

我應該如何才能改變這種ListView綁定聲明(在SecondWindowListView)它與在MainWindowObservableCollection連接?

回答

4

ElementName綁定僅在當前窗口中查找。您需要將Binding Source或(更可能)本地DataContext顯式設置爲該其他窗口。

但是,更好的方法是從Window類中移除ShowQuCollection,並使其成爲單獨的「視圖模型」類(非視覺,僅數據)的一部分。然後,您可以讓兩個Windows都具有相同的DataContext(視圖模型類的一個實例),並且根本不需要使用ElementName綁定。當某些事情依賴於UI中的另一個控件(例如,將Panel的可見性綁定到CheckBox的IsChecked)時,通常使用ElementName綁定,而不是作爲參考實際數據的方式。

0

如果'不同的窗口'表示不同的類,則需要將第二個窗口的DataContext設置爲與第一個窗口的datacontext相同。