c# - 如何在WPF中的DataGrid中获得以编程方式编写的组合框的值?

在这里关注我以前的帖子=> Binding SelectedItem of ComboBox in DataGrid with different type

我现在有一个数据网格,其中包含2列,一列带有文本,另一列带有组合框(在数据模板中,是通过C#代码而不是Xaml编写的)。

在组合框上做了一些选择之后,我现在想解析结果,但是包含我的组合框的单元格的值保持为空:

foreach(DataRowView row in Datagrid1.Items)
{
var firstColumNresult = row.Row.ItemArray[0];// Return correctly a string
var myrow = row.Row.ItemArray[1];// always empty... 
}

结果是我无法获取(先前生成的)组合框的值。

我想在某个地方一定会错过一个绑定(bind)...

这是组合框创建代码:
DataTable tableForDG = new DataTable();
tableForDG.Columns.Add(new DataColumn { ColumnName = "Name", Caption = "Name" });
tableForDG.Columns.Add(new DataColumn { ColumnName = "Attachment", Caption = "Attachment" }); // this column will be replaced
tableForDG.Columns.Add(new DataColumn { ColumnName = "AttachmentValue", Caption = "AttachmentValue" });
tableForDG.Columns.Add(new DataColumn { ColumnName = "DisplayCombo", Caption = "DisplayCombo", DataType=bool });


// Populate dataview
DataView myDataview = new DataView(tableForDG);
foreach (var value in listResults)// a list of string
{
DataRowView drv = myDataview.AddNew();
drv["Name"] = value.Name;
drv["Attachment"] = value.Name;// this column will be replaced...
drv["DisplayCombo"] = true;// but it can be false on my code...
}

var DG = myDataview;// 

 Datagrid1.ItemsSource = DG;
 Datagrid1.AutoGenerateColumns = true;
 Datagrid1.Items.Refresh();

 DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
 dgTemplateColumn.Header = "Attachment";
 var newCombobox = new FrameworkElementFactory(typeof(ComboBox));
 newCombobox.SetValue(ComboBox.NameProperty, "myCBB");

 Binding enableBinding = new Binding();

 newCombobox.SetValue(ComboBox.IsEnabledProperty, new Binding("DisplayCombo")); 
 newCombobox.SetValue(ComboBox.SelectedValueProperty, new Binding("AttachmentValue"));

 List<string> listUnitAlreadyAttached = new List<string>();
 // fill the list...

 enableBinding.Source = listUnitAlreadyAttached;
 newCombobox.SetBinding(ComboBox.ItemsSourceProperty, enableBinding);

 var dataTplT = new DataTemplate();
 dataTplT.VisualTree = newCombobox;
 dgTemplateColumn.CellTemplate = dataTplT;

 Datagrid1.Columns[1] = dgTemplateColumn;

有什么想法/建议吗?

最佳答案

您应明确指定绑定(bind)模式并更新绑定(bind)的触发器。还可以使用SetBinding而不是SetValue:

var valueBinding = new Binding("AttachmentValue")
{
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
newCombobox.SetBinding(ComboBox.SelectedValueProperty, valueBinding);

这应该使您能够将选定的值添加到行数据中。它可能不会在 AttachmentValue列的显示的datagrid值中更新。