【问题标题】:WPF ListView databinding to ObservableCollectionWPF ListView 数据绑定到 ObservableCollection
【发布时间】:2010-01-03 23:15:35
【问题描述】:

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

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

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

我应该如何更改这个ListView 数据绑定声明(SecondWindow 中的ListView)以便与MainWindow 中的ObservableCollection 连接?

【问题讨论】:

    标签: wpf data-binding listview observablecollection


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2017-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        • 1970-01-01
        • 2012-05-26
        • 2018-05-21
        相关资源
        最近更新 更多