【问题标题】:WPF DataGrid Binding property not found未找到 WPF DataGrid 绑定属性
【发布时间】: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 的新实例,然后将该实例作为ListObservableCollection 绑定到您的DataGrid
  • SampleData 应该是 ViewModel 中的一个属性,如下所示:ObservableCollection&lt;SampleData&gt; SampleData {get;set;} 并且不要忘记 INotifyPropertyChanged
  • 你设置了你的Window的DataContext了吗?否则,您的 XAML 会假定您的数据来自 CodeBehind。
  • 我已经用 INotifyPropertyChanged 更新了代码

标签: c# wpf datagrid


【解决方案1】:

SampleData 应该是返回IEnumerable&lt;SampleData&gt;DataGrid(或父元素)的DataContext 的属性。试试这个:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    //set the DataContext of the window itself or the DataGrid
        dgResults.DataContext = new ViewModel();
    }
}

public class ViewModel
{
    public ViewModel()
    {
        SampleData = new List<SampleData>();
        SampleData.Add(new SampleData() { WellID = "1" });
        SampleData.Add(new SampleData() { WellID = "2" });
    }

    public List<SampleData> SampleData { get; }
}

【讨论】:

  • 感谢您的回答。你的意思是List&lt;SampleData&gt; sd = new List&lt;SampleData&gt;(); ??
  • 抱歉,SampleData.Add 出现错误,我在此之前使用 List&lt;SampleData&gt; list = SampleData.ToList(); 解决了该错误。但是我的 DataGrid 是空的,我认为它无法解析 SampleData 因为是放在另一个文件夹中的类
  • 是的,我正在使用您的代码。我刚刚更改了这个 SampleData = new List&lt;SampleData&gt;(); List&lt;SampleData&gt; list = SampleData.ToList(); list.Add(new SampleData() { WellID = "1" });,因为 Add 方法出现错误
  • 您需要设置 SampleData 属性。这是您在视图中绑定的。我的示例代码按原样工作 - 没有理由在列表上调用 ToList()...
  • 抱歉,我看你是WPF专家。正如我所说,我刚刚从 Windows 窗体迁移到 WPF。使用您的代码,我得到“IEnumerable 不包含添加定义”。
猜你喜欢
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 2013-02-28
  • 2017-09-18
  • 1970-01-01
相关资源
最近更新 更多