[英]How to create Dynamic Datagrid columns?
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
what if want is that there is one column perdefined and the others must be dynamical. 如果需要的话,是预定义一列,而其他列必须是动态的。 I need to bind this object to the datagrid. 我需要将此对象绑定到数据网格。 At the the end of the day if must look something like this 最后,如果必须看起来像这样
Variable|Lang(de)|Lang(en) safe |save |speichern close |close |beenden 变量|语言(de)|语言(en)安全|保存| speichern关闭|关闭| beenden
more languages can be inserted. 可以插入更多语言。 it need this for a translation tool 它需要翻译工具
You could do something like this, where you just add the binding. 您可以执行类似的操作,在其中添加绑定。
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; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.