Selecting a cell of a WPF DataGrid which is inside a RowDetailsTemplate
I am experiencing some strange behavior in my datagrid when I have a second datagrid as a rowdetailstemplate. The main datagrid is bound to my collection of items, and the details datagrid is bound to a collection of subitems contained by an item. Now all of this renders perfectly, but when I want to click on a cell in the SubItemsGrid directly, it first selects the first cell of the row in the main grid in which the SubItemsGrid is contained. I have to click a second time to get to the cell I want to select.
Has anyone experencied this as well? And if so, is there a workaround?
This is my mark-up (partially):
<DataGrid x:Name="ItemGrid" ItemsSource="{Binding Path=Items}" AutoGenerateColumns="False" SelectionUnit="Cell"
RowDetailsVisibilityMode="Visible" CanUserResizeRows="False" AreRowDetailsFrozen="False" VerticalAlignment="Top"
CanUserAddRows="False" CanUserDeleteRows="False" VerticalScrollBarVisibility="Hidden">
<DataGrid.Columns>
<DataGridTextColumn Header="Column1" Binding="{Binding Path=ID}" Width="350"/>
<DataGridTextColumn Header="Column2" Binding="{Binding Path=Name}" Width="8开发者_Go百科0"/>
<DataGridTextColumn Header="Column3" Binding="{Binding Path=Description}" Width="80"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DataGrid x:Name="SubItemsGrid" ItemsSource="{Binding Path=SubItems}" AutoGenerateColumns="False"
SelectionUnit="Cell" HeadersVisibility="None" Margin="50,0,0,0" VerticalAlignment="Top" CanUserAddRows="False"
CanUserResizeRows="False" CanUserDeleteRows="False" BorderThickness="0">
<DataGrid.Columns>
<DataGridTextColumn Header="Column1" Binding="{Binding Path=Name}" Width="300" />
<DataGridTextColumn Header="Column2" Binding="{Binding Path=Description}" Width="80"/>
<!-- Etc.-->
---EDIT---
Ok, I came up with the idea to handle the mouse-up event on the SubItemsGrid, and then set the focus to the SubItemsGrid in code, like this:
private void SubItemsGrid_MouseUp(object sender, MouseButtonEventArgs e)
{
DataGrid selectedGrid = sender as DataGrid;
if (selectedGrid != null)
{
selectedGrid.Focus()
}
}
Debugging show that the 'Focus' method gets called on the right grid, but I am not getting any visual results. I get the feeling I am very close to the solution however. Anyone?
I fixed this by catching the 'SelectedCellsChanged' event of the SubItemsGrid. In the handler I called 'BeginEdit()' on the grid that raised the event. This indeed put the focus on the clicked cell directly, but also put the cell in edit mode. That's why I called CancelEdit() directly after. This will keep the focus on the cell, but not in edit mode.
private void SubItemsGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataGrid selectedGrid = sender as DataGrid;
if (selectedGrid != null)
{
selectedGrid.BeginEdit();
selectedGrid.CancelEdit();
}
}
精彩评论