DataGrid.SelectedItem 未绑定到当前选定的单元格

本文关键字:单元格 SelectedItem 绑定 DataGrid | 更新日期: 2023-09-27 17:56:43

多次遇到此问题。

在查找"选定项目"或"选定列"时,请右键单击菜单或在单元格中选择组合框。所选项将为空或先前选择的行。

private void ComboBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
// Correct  
m_BeginEditString = ((ComboBox)sender).SelectedValue.ToString(); 
// Wrong. selected item is last selected row, example clicking directly on combobox will not select row, and be null.
m_BeginEditRow = (RowItem)MyDataGrid.SelectedItem; 
}   
<DataGridTemplateColumn>
   <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <ComboBox SelectedItem="{Binding myItem, Mode=TwoWay, 
NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" 
ItemsSource="{Binding Source={StaticResource enum}}" 
SelectionChanged="ComboBox_Changed" 
LostKeyboardFocus="ComboBox_LostKeyboardFocus" 
GotKeyboardFocus="ComboBox_GotKeyboardFocus" />
        </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

DataGrid.SelectedItem 未绑定到当前选定的单元格

通过完全不同的方式解决,感谢@Ramesh Muthiah 的指导:

private void ComboBox_Changed(object sender, SelectionChangedEventArgs e) {
if (((ComboBox)sender).IsLoaded) { // disregard SelectionChangedEvent fired on population from binding
    if (e.RemovedItems.Count != 0) {
        for (Visual visual = (Visual)sender; visual != null; visual = (Visual)VisualTreeHelper.GetParent(visual)) { // Traverse tree to find corred selected item
            if (visual is DataGridRow) {
                DataGridRow row = (DataGridRow)visual;
                m_BeginEditRow = new MyRowItem((MyRowItem)row.Item); // Copy constructor, otherwise passed by reference
                break;
            }
        }
        MyEnum newItem = (MyEnum)e.AddedItems[0];
        MyEnum oldItem = (MyEnum)e.RemovedItems[0];
        if (m_BeginEditRow.Combo1 == newItem) {
            m_BeginEditRow.Combo1 = oldItem;
        } else {
            m_BeginEditRow.Combo2 = oldItem;
        }
        DoStuff(m_BeginEditRow, false);
    }
}

}

您可以通过

父对象访问并尝试访问所需的任何内容,而不是直接访问选定的项。这是替代方法。我希望这对你有所帮助

Combobox objMyButton = null;
        if (sender is Combobox)
        {
            objMyButton = (sender as Combobox );    
        }
        //You can access the parent object which means corresponding DataGridRow and do whatever you want
        for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
            if (vis is DataGridRow)
            {
                var row = (DataGridRow)vis;                 
                break;
            }