WPF ListView控件绑定到的ObservableCollection [英] WPF ListView databinding to ObservableCollection

查看:758
本文介绍了WPF ListView控件绑定到的ObservableCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF应用程序我有一个的ListView

In WPF app I have a 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 连接:

which is connected with ObservableCollection through databinding:

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 放置在code-背后的同一个窗口,其中的ListView 是文件主窗口。一切工作正常。

This ObservableCollection is placed in the code-behind file of the same window, where ListView is MainWindow. Everything works fine.

现在我想补充的又一的ListView 来不同的窗口,在这种情况下,数据绑定不工作。这一块的数据绑定XAML的我并没有改变:

Now I add yet another ListView to different window and in this case databinding isn't working. This databinding piece of XAML I didn't change:

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

我应该如何改变这种的ListView 绑定声明(的ListView SecondWindow ),它与连接的ObservableCollection 主窗口

How should I change this ListView databinding declaration (ListView in SecondWindow) in order it was connected with the ObservableCollection in the MainWindow?

推荐答案

的ElementName绑定只看当前窗口。您需要明确设置绑定源或(更可能)当地的DataContext到另一个窗口。

ElementName bindings only look in the current window. You would need to set the Binding Source or (more likely) local DataContext explicitly to that other window.

然而,更好的办法是从Window类中删除ShowQuCollection并使其单独的视图模型类(非可视,仅限于数据)的一部分。然后,你可以使双方的Windows具有相同的DataContext(视图模型类的一个实例),你就不需要使用的ElementName都具有约束力。的ElementName绑定通常用于一些依赖于UI(例如绑定面板的能见度为CheckBox的器isChecked),而不是作为一种参照实际的数据。

However, a better approach would be to remove ShowQuCollection from the Window class and make it part of a separate "view model" class (non-visual, data only). Then you could make both Windows have the same DataContext (an instance of the view model class) and you would not need to use an ElementName binding at all. ElementName bindings are typically used when something depends on another control in the UI (e.g. binding a Panel's Visibility to a CheckBox's IsChecked), rather than as a way to refer to actual data.

这篇关于WPF ListView控件绑定到的ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆