0

在 WPF 应用程序中,我有一个ListView

<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被放置在同一窗口的代码隐藏文件中,ListView其中MainWindow. 一切正常。

现在我将另一个添加ListView到不同的窗口,在这种情况下数据绑定不起作用。这个 XAML 的数据绑定部分我没有改变:

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

我应该如何更改此ListView数据绑定声明 ( ListViewin SecondWindow) 以使其与ObservableCollectionin连接MainWindow

4

2 回答 2

4

ElementName 绑定只在当前窗口中查找。您需要将绑定源或(更有可能)本地 DataContext 显式设置为该其他窗口。

但是,更好的方法是从 Window 类中删除 ShowQuCollection 并使其成为单独的“视图模型”类(非可视,仅数据)的一部分。然后,您可以使两个 Windows 具有相同的 DataContext(视图模型类的实例),并且您根本不需要使用 ElementName 绑定。ElementName 绑定通常在某些内容依赖于 UI 中的另一个控件时使用(例如,将 Panel 的 Visibility 绑定到 CheckBox 的 IsChecked),而不是作为引用实际数据的一种方式。

于 2010-01-03T23:26:06.043 回答
0

如果“不同窗口”是指不同的类,则需要将第二个窗口的 DataContext 设置为与第一个窗口的数据上下文相同。

于 2010-01-03T23:19:56.957 回答