【发布时间】:2018-01-08 10:31:37
【问题描述】:
我刚开始使用 WPF,在向 DataGrid 显示数据时遇到问题。
WPF (Views\ResultsPage.xaml):
<DataGrid x:Name="dgResults"
Margin="2"
Style="{DynamicResource AzureDataGrid}"
ItemsSource="{Binding SampleData}"
AutoGenerateColumns="False"
RenderOptions.ClearTypeHint="Enabled"
TextOptions.TextFormattingMode="Display">
<DataGrid.Columns>
<DataGridTextColumn Header="Well" Binding="{Binding WellID}"/>
..
C# (Data\SampleData.cs):
public class : INotifyPropertyChanged
{
private string _wellID;
public string WellID
{
get
{
return _wellID;
}
set
{
_wellID = value;
NotifyPropertyChanged("WellID");
}
}
...
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
我收到此错误: System.Windows.Data Error: 40 : BindingExpression path error: 'SampleData'
【问题讨论】:
-
您需要创建一个
SampleData的新实例,然后将该实例作为List或ObservableCollection绑定到您的DataGrid。 -
SampleData 应该是 ViewModel 中的一个属性,如下所示:
ObservableCollection<SampleData> SampleData {get;set;}并且不要忘记INotifyPropertyChanged -
你设置了你的Window的DataContext了吗?否则,您的 XAML 会假定您的数据来自 CodeBehind。
-
我已经用 INotifyPropertyChanged 更新了代码