【问题标题】:How to: wpf datagrid totally programmatical, including binding to observablecollection如何:完全编程的 wpf datagrid,包括绑定到 observablecollection
【发布时间】:2015-11-02 09:44:34
【问题描述】:

我必须在代码中执行整个事情,并且在 StackOverflow 和亲爱的谷歌叔叔中花费了两句后不知所措。

我有一个课程TestData:InotifyPropertyChanged,其中包括一个string“名称”、另一个string“详细信息”和一个bool array“检查”。该类用于构建静态Observablecollection“testData”(小写)。

我想通过代码创建一个datagrid,而不是让它自动列,并呈现这些列:

  1. DataGridTextColumn 带有“名称”,不可编辑。
  2. DataGridTextColumn 带有“详细信息”,可编辑(并显示默认值“-”)。
  3. 三个带有“检查”数据的DataGridCheckBoxColums。

结构设置正确,并显示所需的标题和数据占位符。有一个按钮可以将新记录添加到“testData”,并且确实将其他行添加到数据网格中,但遗憾的是这些都是空的。

显然,我需要这是双向的。

我无法显示我在“testData”声明中为“细节”和“检查”设置的值。

此外,我不断收到一条错误消息,提示“双向绑定需要 Path 或 x:path”。好郁闷……

这是我尝试过的:

<DataGrid x:Name="dgMainDataGrid" CanUserAddRows="False" AutoGenerateColumns="False" />

dgMainDataGrid.ItemsSource = testData;

DataGridTextColumn col1 = new DataGridTextColumn();
col1.Header = "col1Header";
col1.IsReadOnly = true;
col1.Binding = new Binding("Name");

DataGridTextColumn col2 = new DataGridTextColumn();
col2.Header = "col2Header";
col2.IsReadOnly = false;
col2.Binding = new Binding("Specifics");

DataGridCheckBoxColumn col3 = new DataGridCheckBoxColumn();
col3.Header = "col3Header";
col3.IsReadOnly = false;
col3.Binding = new Binding("checks[0]");


DataGridCheckBoxColumn col4 = new DataGridCheckBoxColumn();
col4.Header = "col3Header";
col4.IsReadOnly = false;
col4.Binding = new Binding("checks[1]");

DataGridCheckBoxColumn col5 = new DataGridCheckBoxColumn();
col5.Header = "col3Header";
col5.IsReadOnly = false;
col5.Binding = new Binding("checks[2]");

和类

public class TestData : INotifyPropertyChanged
{
public string Name;
public string Specifics;
public bool[] checks;
}

谢谢各位。

【问题讨论】:

标签: wpf binding datagrid observablecollection programmatically-created


【解决方案1】:

@Clemens 询问我的班级的外观后,我发现这些不是属性。洒一些{get; set;} 在字段上。

【讨论】:

    猜你喜欢
    • 2013-10-14
    • 2014-08-23
    • 2015-01-26
    • 2015-04-02
    • 2021-08-31
    • 2016-09-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多