WPF开发:如何在两个ColumnDefinition间传递DataGrid选中单元格数据
实现方案
1. 给ViewModel新增选中项绑定属性
在你的页面绑定的ViewModel类中添加用于接收DataGrid选中项的属性,需配合INotifyPropertyChanged接口实现UI变更通知:
// 此处泛型替换为你实际使用的Observable Dictionary的Key、Value类型 private KeyValuePair<PersonKey, PersonValue> _selectedPerson; public KeyValuePair<PersonKey, PersonValue> SelectedPerson { get => _selectedPerson; set { _selectedPerson = value; // 调用你项目中封装的属性变更通知方法,示例为通用写法 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedPerson))); } }
如果你绑定DataGrid的
ItemsSource用的是Persons.Values,则上述属性的类型直接替换为你Dictionary的Value类型即可,无需用KeyValuePair包裹。
2. 修改XAML代码
调整原有XAML,添加选中项绑定和第二列的详情展示区域:
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <DataGrid ItemsSource="{Binding Persons.Values}" AutoGenerateColumns="False" Grid.Column="0" SelectedItem="{Binding SelectedPerson}" <!-- 配置点击单元格即触发选中,无需选中整行 --> SelectionUnit="CellOrRowHeader"> <DataGrid.Columns> <DataGridTemplateColumn SortMemberPath="Key.Name" Header="K1 Regler" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Border Background="Azure"> <Grid> <Label Foreground="Black" Content="{Binding Path=Key.Name}" Width="Auto" HorizontalContentAlignment="Center"/> </Grid> </Border> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <!-- 第二列详情展示区,绑定你需要展示的属性即可 --> <StackPanel Grid.Column="1" Margin="20"> <TextBlock Text="详情信息" FontSize="18" FontWeight="Bold" Margin="0 0 0 15"/> <TextBlock Text="{Binding SelectedPerson.Key.Name, StringFormat='名称:{0}'}" Margin="0 5"/> <TextBlock Text="{Binding SelectedPerson.Value.Description, StringFormat='描述:{0}'}" Margin="0 5"/> <TextBlock Text="{Binding SelectedPerson.Value.CreateTime, StringFormat='创建时间:{0:yyyy-MM-dd}'}" Margin="0 5"/> <!-- 其他需要展示的属性自行补充即可 --> </StackPanel> </Grid>
配置完成后只要你选中DataGrid的任意单元格,对应数据项会自动同步到SelectedPerson属性,第二列会自动更新展示对应详情,无需额外写传值逻辑。
内容的提问来源于stack exchange,提问作者MalinaStempel
相关产品推荐
相关产品推荐

