【发布时间】:2018-08-24 17:24:21
【问题描述】:
我正在尝试从 DataGrid 表中的可编辑组合框中获取单元格值。从选项中选择项目时成功/正确提取值,但当用户在组合框中输入文本时不会(除非他们双击)
问题:RowIndex 变为-1(在单击文本条目时),好像没有选择一行,导致代码失败,并错误地处理更新。
我该如何解决这个问题?如果强制用户双击是一个有效的选项,我该怎么做?
这是我的 C# 代码:
private void ComboBox_LostFocus(object sender, RoutedEventArgs e)
{
if (e != null)
{
TextBox t = e.Source as TextBox;
if (t != null)
{
try
{
int RowIndex = MYGRID.Items.IndexOf(MYGRID.SelectedItem);
if (RowIndex < 0)
{
MessageBox.Show("Index < 0"); //For Testing
}
//Obtain new Value
string Value = t.Text.ToString();
//Obtain item ID
DataGridRow Row = (DataGridRow)MYGRID.ItemContainerGenerator.ContainerFromIndex(RowIndex);
DataGridCell RowColumn = MYGRID.Columns[0].GetCellContent(Row).Parent as DataGridCell;
int ID = Convert.ToInt32(((TextBlock)RowColumn.Content).Text);
//Unrelated code continues...
}
catch (Exception) { }
}
}
}
这是我的列的 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="True" LostFocus="ComboBox_LostFocus" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
【问题讨论】:
-
我刚刚测试了你的情况,我可以确认网格上的选定项目没有被设置。您是否尝试过使用
VisualTreeHelper来获取DataGridRow的父类型? -
我该怎么做?
-
google
wpf find parent你会发现一个特定类型的父母的recursive搜索,一旦你拥有它然后设置选定的属性。然后您的绑定将启动,并且网格中选定项目的属性将具有当前选定的项目。