【发布时间】:2019-01-31 02:18:58
【问题描述】:
我正在尝试获取 DataGrid 表中的单元格值,但在将列设置为 TemplateColumn 后出现错误。以前,我将列作为 ComboBoxColumn,并且我的代码有效。
这是我的 C# 代码:
DataGridRow Row = (DataGridRow)MYGRID.ItemContainerGenerator.ContainerFromIndex(MYGRID.SelectedIndex);
RowColumn = MYGRID.Columns[4].GetCellContent(Row).Parent as DataGridCell;
string Value = ((ComboBox)RowColumn.Content).Text;
这是我的列的 XAML 代码:
<DataGridTemplateColumn x:Name="ValueCol" Header="Value" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Options, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Path=UpdatedData, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True}" IsEditable="False" LostFocus="ComboBox_LostFocus" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
更新值时,出现以下错误:
'Unable to cast object of type 'System.Windows.Controls.ContentPresenter' to type 'System.Windows.Controls.ComboBox'.'
编辑:能够通过创建 LostFocus 事件并从 RoutedEventArgs 对象中提取数据来获取新值。
【问题讨论】:
-
为什么要混合使用代码隐藏和绑定?
-
请问克里斯您的要求是什么?从您的 c# 代码中,我可以理解,您正在尝试获取所选单元格的文本。对吗?
-
@KevinCook 我这样做是因为我正在更新其他事件
-
@Karuppasamy 我实际上能够使用不同的方法获得值
-
@Chris,您正在尝试将作为内容呈现器的 RowColumn.Content 转换为组合框,这可能是给定错误的原因。
标签: c# wpf combobox datagrid datagridtemplatecolumn