【问题标题】:Selecting a cell of a WPF DataGrid which is inside a RowDetailsTemplate选择 RowDetailsTemplate 内的 WPF DataGrid 的单元格
【发布时间】:2010-12-07 13:09:39
【问题描述】:

当我有第二个数据网格作为 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上处理鼠标向上事件的想法,然后在代码中将焦点设置到SubItemsGrid,像这样:

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

调试显示“焦点”方法在正确的网格上被调用,但我没有得到任何视觉结果。然而,我觉得我非常接近解决方案。有人吗?

【问题讨论】:

    标签: c# .net wpf datagrid


    【解决方案1】:

    我通过捕获 SubItemsGrid 的“SelectedCellsChanged”事件解决了这个问题。在处理程序中,我在引发事件的网格上调用了“BeginEdit()”。这确实将焦点直接放在单击的单元格上,但也将单元格置于编辑模式。这就是我之后直接调用 CancelEdit() 的原因。这会将焦点保持在单元格上,但不会处于编辑模式。

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

    【讨论】:

    • 第一次点击的吞咽是我自己亲眼所见的,尽管没有子网格。它还在this sliverlight.net thread 中进行了评论。请注意,我还没有想出一个通用的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2013-12-22
    • 2014-06-24
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多