Reputation: 1158
In my datagrid
, one of columns is DataGridComboBoxColumn
, where I'm trying to display different drop down menu in every row. Easy task when creating combo box in XAML instead of doing it programatically. My problem is that I have no idea how to bind it properly. This is what I tried:
private DataGridComboBoxColumn CreateComboValueColumn(List<Elements> elements)
{
DataGridComboBoxColumn column = new DataGridComboBoxColumn();
column.ItemsSource = elements;
column.DisplayMemberPath = "Text";
column.SelectedValuePath = "ID";
column.SelectedValueBinding = new Binding("Value");
return column;
}
public class Elements
{
public string Name { get; set; }
public string Value { get; set; }
public string Comment { get; set; }
public List<ComboItem> ComboItems { get; set; }
}
public class ComboItem
{
public string ID { get; set; }
public string Text { get; set; }
}
Upvotes: 1
Views: 1797
Reputation: 1
You can use the following as an example:
ComboBox dgvCmb = new ComboBox();
dgvCmb.Name = "Name";
dgvCmb.Items.Add("Razali");
dgvCmb.Items.Add("Boeing");
dgvCmb.Items.Add("Londang");
dgvCmb.Items.Add("MCKK");
DataGridComboBoxColumn dgc=new DataGridComboBoxColumn();
dgc.Header = "Test";
dgc.ItemsSource = dgvCmb.Items;
dataGrid.Columns.Add(dgc);
Upvotes: 0
Reputation: 1158
It seems that adding binding from style
works better than direct approach. This works:
private DataGridComboBoxColumn CreateComboValueColumn(List<Elements> elements)
{
DataGridComboBoxColumn column = new DataGridComboBoxColumn();
Style style = new Style(typeof(ComboBox));
//set itemsource = {Binding ComboItems}
style.Setters.Add(new Setter(ComboBox.ItemsSourceProperty, new Binding("ComboItems")));
column.DisplayMemberPath = "Text";
column.SelectedValuePath = "ID";
column.SelectedValueBinding = new Binding("Value");
column.ElementStyle = style;
column.EditingElementStyle = style;
return column;
}
Upvotes: 0
Reputation: 784
You have to think from above and read what you are doing.
column.ItemsSource = elements;
That sets your column itemssource to a list of elements.
column.DisplayMemberPath = "Text";
It's not a member of Element so it won't show anything. You should set your column.ItemsSource to:
column.ItemsSource = elements[i].ComboItems
Being "i" the element you want to show.
Then if you want to show the text you should:
column.DisplayMemberPath = "Text";
If you want the Id then just:
column.DisplayMemberPath = "ID";
I wrote this without any editor and I think this is close to the answer you want, if I'm wrong comment this and I'll try to answer in a more accurate way.
Upvotes: 1