I'm using the MVVM pattern for a simple WPF app. My View has a DataGrid and a Button. My DataGrid has an Attached Property (the purpose of the Attached Property isn't really pertinent to my question).
If I click a cell in the DataGrid and then click the Button, my Attached Property's "OnIsCurrentCellFocusedPropertyChanged" method executes. Here's a snippet from this method:
public static void OnIsCurrentCellFocusedPropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
// This works; I confirmed it's returning the actual DataGrid in my view
// and not another "new" instance of DataGrid.
var datagrid = source as DataGrid;
if (!(bool)e.NewValue) return;
// datagrid.CurrentCell is null!
DataGridColumn cellColumn = datagrid.CurrentCell.Column;
int colNumber = cellColumn.DisplayIndex;
// datagrid.SelectedIndex is -1!
int rowNumber = datagrid.SelectedIndex;
// more code....
}
XAML snippet showing the AttachedProperty in my DataGrid:
<DataGrid FrozenColumnCount="1" local:CurrentCellFocusedExtension.IsCurrentCellFocused="{Binding IsFocused}" x:Name="companies" ItemsSource="{Binding Companies}"/>
My problem is, I want to get the CurrentCell from my DataGrid, but CurrentCell == null. I suppose this is because when I click the Button, focus shifts to the Button and away from my DataGrid (though the cell is still visibly selected in the view). Also troubling is SelectedIndex returns -1... I can't even get the row index, let alone the selected cell.
Help?
A thought: I could probably subclass DataGrid and add a public "last selected cell" property.
BeginEdit
andAcceptEdit
/RevertEdit
methods) and by creating my own version of WF4's ModelItem, which wraps POCOs and provides update notification, attached properties, and other UI-centric support like undo/redo tracking. As for this version.... not sure if it would be workable due to the limited surface you have to work with on the DG. Perhaps extend the DG to add undo/redo instead? – user1228