我正在尝试从创建自定义 DataGrid 的 ItemsSource复制解决方案,但我的行没有填充。
列显示正确的标题,但网格中没有数据。
谁能告诉我我做错了什么?
using System;
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
namespace WPFBindingDataGridTest2
{
public partial class MainWindow : Window
{
public ObservableCollection<MyObject> myList { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
testClass = new ObservableCollection<TestClass>();
testClass.Add(new TestClass(NameValue: "John"));
testClass.Add(new TestClass(NameValue: "Frank"));
testClass.Add(new TestClass(NameValue: "Sarah"));
testClass.Add(new TestClass(NameValue: "David"));
}
}
class TestClass : INotifyPropertyChanged
{
private string name;
public TestClass(string NameValue)
{
this.Name = NameValue;
}
public String Name
{
get { return name; }
set { this.name = value; NotifyPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
和 XAML...
<Grid>
<DataGrid x:Name="dataGrid" ItemsSource="{Binding testClass}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
我得到的错误是
System.Windows.Data Error: 40 :
BindingExpression path error:
'testClass' property not found on 'object'''MainWindow'
(Name='')'.BindingExpression:
Path=testClass;
DataItem='MainWindow' (Name='');
target element is 'DataGrid' (Name='dataGrid');
target property is 'ItemsSource' (type 'IEnumerable')
我觉得我很接近这个,但我只是错过了一件事。
可能数据上下文是错误的?