I've written a simple example in which a DataGrid
on a WPF form is populated entirely from the codebehind. A DataGridTemplateColumn
with a ComboBox
has the ItemsSource
set to a DummyClass
that contains two properties for the DisplayMember
and the SelectedValue
.
A DataTable
is populated with a single column
with two rows
. The ItemsSource
for the DataGrid
is set to the default view of the DataTable
.
When the code runs, each ComboBox
in the DataGrid
displays correctly and has the proper options available in the dropdown
but does not display the values from the DataTable
.
What binding am I missing to connect the ComboBox
SelectedValue
to the values from the DataTable
?
public partial class MainWindow : Window
{
public class DummyClass
{
public int SelectedValue { get; set; }
public string DisplayValue { get; set; }
}
public ObservableCollection<DummyClass> DummyClassCollection;
public MainWindow()
{
InitializeComponent();
DummyClassCollection = new ObservableCollection<DummyClass>();
DummyClassCollection.Add(new DummyClass() { DisplayValue = "Item1", SelectedValue = 0 });
DummyClassCollection.Add(new DummyClass() { DisplayValue = "Item2", SelectedValue = 1 });
DummyClassCollection.Add(new DummyClass() { DisplayValue = "Item3", SelectedValue = 2 });
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
DataTemplate dataTemplate = new DataTemplate();
FrameworkElementFactory control = new FrameworkElementFactory(typeof(ComboBox));
control.SetValue(ComboBox.ItemsSourceProperty, DummyClassCollection);
control.SetValue(ComboBox.DisplayMemberPathProperty, "DisplayValue");
//
//Some binding to connect ComboBox Selectedvalue to DataTable values
//
dataTemplate.VisualTree = control;
templateColumn.CellTemplate = dataTemplate;
templateColumn.Header = "DummyColumn";
dgGrid.Columns.Add(templateColumn);
DataTable table = new DataTable();
table.Columns.Add("DummyColumn");
table.Rows.Add(1);
table.Rows.Add(2);
dgGrid.AutoGenerateColumns = false;
dgGrid.ItemsSource = table.DefaultView;
}
}
Here is all you need...
control.SetValue(ComboBox.DisplayMemberPathProperty, "DisplayValue");
control.SetValue(ComboBox.SelectedValuePathProperty, "SelectedValue");
control.SetValue(ComboBox.SelectedValueProperty, new Binding("DummyColumn"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.