【问题标题】:Dynamically bind grid in WPF在 WPF 中动态绑定网格
【发布时间】:2015-02-04 10:54:38
【问题描述】:

我无法查看我动态绑定到的网格中的行,这是我的代码

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DisplayGrid();
    }

    private void DisplayGrid()
    {
        var records = new ObservableCollection<Record>();
        records.Add(new Record(new Property("FirstName", "ABC"), new Property("LastName", "DEF")));
        records.Add(new Record(new Property("FirstName", "GHI"), new Property("LastName", "JKL")));

        var columns = records.First()
            .Properties
            .Select((x, i) => new { Name = x.Name, Index = i })
            .ToArray();

        foreach (var column in columns)
        {
            var binding = new Binding(string.Format("Properties[{0}].Value", column.Index));
            dataGrid.Columns.Add(new DataGridTextColumn() { Header = column.Name, Binding = binding });
        }
    }
}

class Record
{

    readonly ObservableCollection<Property> _properties = new ObservableCollection<Property>();

    public Record(params Property[] properties)
    {
        foreach (var property in properties)
        {
            _properties.Add(property);
        }
    }

    public ObservableCollection<Property> Properties
    {
        get { return _properties; }
    }


}

在我的 XAML 中

       <DataGrid
        Name="dataGrid"
        AutoGenerateColumns="False"
        ItemsSource="{Binding Path=Records}"/>

我只能在我的网格中显示标题,但不能在行中显示..

谢谢

【问题讨论】:

  • 发布你的 Record 课程

标签: c# wpf


【解决方案1】:

您需要将一个可观察的集合 Records 作为公共属性添加到您的 MainWindow:

public ObservableCollection<Record> Records {get; set;}

并使用它来代替私有变量records。还将DataContext = this; 添加到构造函数中。

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2011-02-23
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多