In WinForm DataGridView, it automatically selects the first row when initialized. It drove me crazy when I tried to turn that feature off. Moving to WPF DataGrid, it seems Microsoft has decided to turn this feature off, which is a good thing I think. However, I have hard time to enable this feature now. For some DataGrid, I want the first row to be selected automatically after grid is populated through data binding. There are some suggestions in Internet, but I couldn't make that work. I hope for better luck here.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
You can do this consistently in the DataGrid.Loaded event. Just obtain the first row and have the row fire the selection event.
I'm not sure this is a bug because you may not be guaranteed to have selection events fire from your object until the control is loaded. Don't know.
I'm glad to report I found a solution for this problem through
ItemContainerGenerator.StatusChanged
event.It looks when this event is fired with status ContainersGenerated, dataGrid is fully initialized. To me, this is more like DataGridView's DataBindingComplete event in WinForm. If so, the "
DataContextChanged
" event should really be called "DataContextChanging
" event.This was inspired by a post here I accidently found while looking for another clue.
You could try this.
Set
IsSynchronizedWithCurrentItem = "true"
.EDIT:
To address your comment, I assume that your DataGrid's SelectionUnit is set to "Cell", is it? Okay, I'm not sure if this is the best solution but one thing you can do is handle the Loaded event for the DataGrid and manually set the selected cell in the code-behind. So you'll have something like this:
Event-Handler:
Note that this will only work if the DataGrid.SelectionUnit is set to "Cell". Otherwise, I believe it will throw an exception.
EDIT2:
XAML:
Code-Behind: