繁体   English   中英

选择位于RowDetailsTemplate内的WPF DataGrid的单元格

[英]Selecting a cell of a WPF DataGrid which is inside a RowDetailsTemplate

当我有第二个数据网格作为rowdetails模板时,我的数据网格中出现了一些奇怪的行为。 主数据网格绑定到我的项目集合,而细节数据网格绑定到一个项目包含的子项目的集合。 现在,所有这些都可以完美呈现,但是当我想直接单击SubItemsGrid中的单元格时,它将首先选择包含SubItemsGrid的主网格中该行的第一个单元格。 我必须再次单击才能进入要选择的单元格。

有人也有经验吗? 如果是这样,是否有解决方法?

这是我的标记(部分):

<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="80"/>
        <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.--> 

- -编辑 - -

好的,我想到了处理SubItemsGrid上的mouse-up事件的想法,然后将焦点设置为代码中的SubItemsGrid,如下所示:

private void SubItemsGrid_MouseUp(object sender, MouseButtonEventArgs e)
{
   DataGrid selectedGrid = sender as DataGrid;
   if (selectedGrid != null)
   {
       selectedGrid.Focus()
   }
}

调试表明,“ Focus”方法在正确的网格上被调用,但是我没有得到任何视觉结果。 我感觉到我非常接近解决方案。 任何人?

我通过捕获SubItemsGrid的'SelectedCellsChanged'事件来解决此问题。 在处理程序中,我在引发事件的网格上调用了“ BeginEdit()”。 实际上,这确实将焦点直接放在了单击的单元格上,但也使该单元格处于编辑模式。 这就是为什么我之后直接调用CancelEdit()的原因。 这将使焦点集中在单元格上,但不在编辑模式下。

private void SubItemsGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
   DataGrid selectedGrid = sender as DataGrid;
   if (selectedGrid != null)
   {
       selectedGrid.BeginEdit();
       selectedGrid.CancelEdit();
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM