大家好...
我的想法是将DataGrid用作映射模板,首先该表格将从“表A”中加载数据,其中一列将显示来自“表B”的数据。
我有一个像这样的“表B”:
fieldtype_id | fieldtype_name
1 int
2 varchar
3 date
我可以帮您将此表格显示在WPF数据网格中,使用DataGridComboBoxColumn。
因此,我创建了一个WPF窗口和一个其中的datagrid,下面是XAML代码:
<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="12,123,0,176" Name="dataGrid1" Width="1000"
ItemsSource="{Binding}" SelectionUnit="CellOrRowHeader" CanUserAddRows="False"
CellEditEnding="dataGrid1_CellEditEnding" CurrentCellChanged="dataGrid1_CurrentCellChanged">
<DataGrid.Columns>
<DataGridComboBoxColumn
Header="Field Type" Width="200"
DisplayMemberPath="Value"
SelectedValueBinding="{Binding fieldtypeSS, Mode=TwoWay}"
SelectedValuePath="{Binding fieldtype_id}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="IsSynchronizedWithCurrentItem" Value="False" />
<Setter Property="ItemsSource" Value="{Binding Path=fieldtype_id}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=fieldtype_id}" />
<Setter Property="IsDropDownOpen" Value="True" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
然后,我创建了一个类:
public class cMapHeader
{
public int fieldtypeSS { get; set; }
public Dictionary<string, string> fieldtype_id { get; set; }
}
然后,使用我之前创建的方法填充表格。
//## Get MysqlFieldType
//## dboperation.dtQueries is my method to populate data, and return as DataTable
Dictionary<string, string> mysqlFieldType = new Dictionary<string, string>();
foreach (DataRow row in dboperation.dtQueries("SELECT fieldtype_id, fieldtype_name FROM mysql_Fieldtype ").Rows)
{
mysqlFieldType.Add(row["fieldtype_id"].ToString(), row["fieldtype_name"] as string);
}
接下来,填充网格
gridMapHeader = new ObservableCollection<cMapHeader>()
{
new cMapHeader(){fieldtypeSS="1",fieldtype_id=mysqlFieldType},
new cMapHeader(){fieldtypeSS="2",fieldtype_id=mysqlFieldType}
};
dataGrid1.BeginInit();
dataGrid1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding
{
Source = gridMapHeader
});
问题出在应该包含fieldtypeSS的单元格没有显示出来,但是在编辑模式下,DataGridComboBoxColumn可以正确地显示我想要的值(只显示“表B”的fieldtype_name)。
然后第二个问题是,当单元格失去焦点时,从DataGridComboBoxColumn选择的值会丢失。
有人能帮我吗?
非常感谢任何帮助:D
谢谢!