我已经使用DataGridTemplateColumns
创建了一个数据网格。我想访问datagrid单元格的值。
这是我的Xaml代码:
<DataGrid x:Name="dgMappingColumns" Height="180" Width="450" SelectionMode="Extended" SelectionUnit="FullRow" ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserAddRows="False" PreparingCellForEdit="dgMappingColumns_PreparingCellForEdit">
<DataGrid.Columns>
<DataGridTemplateColumn Header="CSVColumn">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox x:Name="txtbDataColumn" Width="140" Text="{Binding DataColumn}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="ExcelColumn">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox x:Name="cmbExcelColumn"
ItemsSource="{Binding ExcelColumn}"
Width="220"
SelectedItem="ExcelColumn"
SelectionChanged="cmbExcelColumn_SelectionChanged"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Required">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox x:Name="cmbRequired"
ItemsSource=
"{Binding Required}"
SelectedItem="Required"
SelectionChanged="cmbRequired_SelectionChanged"
/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
以下是我尝试从datagrid访问每个单元格值的代码。
private void btnSave_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < dgMappingColumns.Items.Count; i++)
{
TextBlock a = dgMappingColumns.Columns[0].GetCellContent(dgMappingColumns.Items[i]) as TextBlock;
string aa = a.Text;
}
此外,我将以下类的绑定列表添加到datagrid以生成行。
即。public List<DataGridRowSet> DataGridRowSets { get; set; }
public class DataGridRowSet
{
public string DataColumn { get; set; }
public ObservableCollection<string> ExcelColumn { get; set; }
public ObservableCollection<string> Required { get; set; }
}