简单的ListView数据绑定

我正在尝试使用WPF和C#在ListView显示数据,我对我看到的不同示例和方法感到困惑。 我正在寻找一个类似于我的程序的完整工作示例,或者一个使它工作的先决条件列表。 如果我设法只显示我的collections中的一行数据,我会很高兴。 目前,列表视图不显示任何内容。

C#:

 public partial class MainWindow : Window { public ObservableCollection Rows { get; set; } public MainWindow() { InitializeComponent(); Rows = new ObservableCollection(); Rows.Add(new Row { ID = "42", Category = "cat", CharLimit = 32, Text = "Bonjour" }); } } public class Row { public string ID { get; set; } public string Category { get; set; } public int CharLimit { get; set; } public string Text { get; set; } } 

XAML:

          

提前致谢

创建一个viewmodel ,可以将其设置为XAML的数据上下文

  public class WindowsViewModel { private ObservableCollection m_Rows; public ObservableCollection Rows { get { return m_Rows; } set { m_Rows = value; } } public WindowsViewModel() { Rows = new ObservableCollection(); Rows.Add(new RowViewModel { ID = "42", Category = "cat", CharLimit = 32, Text = "Bonjour" }); } } 

以下面的方式实现类RowViewModel

  public class RowViewModel:INotifyPropertyChanged { public RowViewModel() { } private string m_ID; public string ID { get { return m_ID; } set { m_ID = value; NotifyPropertyChanged("ID"); } } public string Category { get; set; } public int CharLimit { get; set; } public string Text { get; set; } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string Obj) { if (PropertyChanged != null) { this.PropertyChanged(this,new PropertyChangedEventArgs(Obj)); } } } 

在XAML背后的代码中,添加代码:

 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new WindowsViewModel(); } } 

在listview节点中添加更新源触发器属性:

         

您必须指定源,否则,就像您的情况一样,它将在当前上下文中查找属性,默认情况下,如果没有指定其他内容,则将是DataContext 。 尝试这样的事情:

  

就像你指定它应该在当前Window查找Rows