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

时间:2013-01-29 15:08:51

标签: c# xaml binding datagrid

多次涉及这个问题。

在单击右键菜单或在单元格中选择组合框时找到SelectedItem或选定列。 SelectedItem将为null或先前选定的行。

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>

2 个答案:

答案 0 :(得分:1)

您可以通过父对象访问并尝试访问您想要的任何内容,而不是直接访问所选项目。这是另一种方法。我希望这可以帮助你

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;
            }

答案 1 :(得分:1)

通过完全不同的方式解决,感谢@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);
    }
}

}