如何创建动态Datagrid列?

时间:2018-07-02 15:25:29

标签: c# wpf datagrid wpfdatagrid

public partial class MainWindow : Window
{
    public ObservableCollection<MainEntry> mainEntries { get; set; }
    public MainWindow()
    {
        mainEntries = new ObservableCollection<MainEntry>();
        for (int i = 1; i < 3; i++)
        {
            MainEntry mainEntry = new MainEntry();
            if (i == 1)
            {
                mainEntry.Variable = "safe";
                mainEntry.LangEntries.Add(new LangEntry { Entry = "speichern", Lang = "de" });
                mainEntry.LangEntries.Add(new LangEntry { Entry = "safe", Lang = "en" });
            }
            else if (i == 2)
            {
                mainEntry.Variable = "close";
                mainEntry.LangEntries.Add(new LangEntry { Entry = "beenden", Lang = "de" });
                mainEntry.LangEntries.Add(new LangEntry { Entry = "close", Lang = "en" });
            }
            mainEntries.Add(mainEntry);
        }
        this.DataContext = this;
        InitializeComponent();

    }

}
public class MainEntry
{
    string _variable = null;
    ObservableCollection<LangEntry> _langEntries = null;

    public MainEntry()
    {
        LangEntries = new ObservableCollection<LangEntry>();
    }

    public string Variable { get => _variable; set => _variable = value; }
    public ObservableCollection<LangEntry> LangEntries { get => _langEntries; set => _langEntries = value; }
}

public class LangEntry
{
    private string _lang = null;
    private string _entry = null;


    public string Lang { get => _lang; set => _lang = value; }
    public string Entry { get => _entry; set => _entry = value; }
}enter code here

如果需要的话,是预定义一列,而其他列必须是动态的。我需要将此对象绑定到数据网格。 最后,如果看起来像这样

变量| Lang(de)| Lang(en) 安全|保存|专用 关闭|关闭| beenden

可以插入更多语言。转换工具需要它

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作,只需在其中添加绑定即可。

public partial class MainWindow : Window
{

    public ObservableCollection<Person> Items  = new ObservableCollection<Person>();

    public MainWindow()
    {
        InitializeComponent();

        Items.Add(new Person(){FirstName = "James", LastName = "Tays"});

        this.DataGrid.ItemsSource = Items;
    }

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        if (this.DataGrid.Columns.Any())
        {
            var binding = new Binding("LastName");
            this.DataGrid.Columns.Add(new DataGridTextColumn(){Header = "Last Name", Binding = binding});
        }
        else
        {
            var binding = new Binding("FirstName");
            this.DataGrid.Columns.Add(new DataGridTextColumn(){Header = "FirstName", Binding = binding});
        }
    }
}

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}
}