如何在 wpf 的数据网格中获取以编程方式编写的组合框的值?

How to get value of a programmatically written combobox in a datagrid in wpf?

在这里跟随我之前的 post => 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... 
}

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

我想一定是某处遗漏了一个绑定...

这是组合框创建代码:

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;

有 idea/advice 吗?

您应该明确指定绑定的绑定模式和更新触发器。还使用 SetBinding 而不是 SetValue:

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

这样您就可以将所选值添加到行数据中。它可能不会在 AttachmentValue 列的显示数据网格值中更新。