【问题标题】:WPF DataGrid filtered items, jumpy scrollbarWPF DataGrid 过滤的项目,跳跃的滚动条
【发布时间】:2016-04-09 17:54:25
【问题描述】:

我有一个 DataGrid 和一个 ItemSource 填充控件。我还使用过滤器/查询机制来过滤控件的内容。

当数据网格未被过滤时,滚动工作正常。但是当我过滤(=将项目的可见性设置为false,这会折叠数据网格中的项目)时,滚动变得非常“跳跃”。当我向下滚动时,滚动条变得越来越小,滚动成为一种烦人的体验。

我读到了一些关于virtualization 的内容,以及一些关于设置DataGrid.ScrollViewer 的内容,但是我在XAML 中没有这些属性。

为什么感觉微不足道的东西却过于复杂......无论如何,我如何将我的数据网格配置为:

  • 通过数据绑定显示项目列表
  • 能够过滤列表(通过折叠项目)
  • 显然有一个滚动条,允许用户滚动而不会感到沮丧:)

我的 XAML:

<DataGrid Grid.Row="2"
          ItemsSource="{Binding ErrorsThatStoppedMachine}"
          AutoGenerateColumns="False"
          SelectedItem="{Binding SelectedError}"
          IsReadOnly="True"
          SelectionMode="Single">

    <DataGrid.Columns>
        <DataGridTextColumn Header="Timestamp" Width="220" Binding="{Binding Path=Timestamp}" />
        <DataGridTextColumn Header="ErrorCode" Width="90" Binding="{Binding Path=ErrorCode}" />
        <DataGridTextColumn Header="Unit" Width="70" Binding="{Binding Path=Unit}" />
        <DataGridTextColumn Header="State" Width="100" Binding="{Binding Path=MachineState}" />
        <DataGridTextColumn Header="Message" Width="*" Binding="{Binding Path=Message}" />
    </DataGrid.Columns>

    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}"
               d:DataContext="{d:DesignInstance IsDesignTimeCreatable=True, Type=viewModels:ErrorViewModel}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsVisible}" Value="false">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

提前非常感谢。

PS:非常感谢您提供一些额外的解释,如果能从中真正学到一些东西,那将是一个不错的奖励......

【问题讨论】:

    标签: c# wpf xaml datagrid


    【解决方案1】:

    DataGrid 有一个ViewPort,并且只会渲染和计算实际显示的内容。这被称为虚拟化。取决于行/单元格数据的视觉变化将不可避免地导致“跳跃”,因为 DataGrid 会在现场计算它们。

    Scrollviewer 上的设置以及将网格放在Scrollviewer 中都会禁用虚拟化。这意味着将立即渲染整个网格:

    • 网格可以平滑滚动
    • Grid 的初始加载时间会更长:如果附加到网格的数据过多,它将变得无法使用。

    如果您的 Grid 只包含有限数量的行,这可能没问题。


    解决此问题的更好方法是直接在ItemsSource 上进行过滤。使用ObservableCollection 并在那里过滤您的数据。网格将根据ObservableCollection 显示行。

    这正是您使用设置可见性的 RowStyle 重建的行为。

    【讨论】:

    • 这真的很有帮助!肯定会考虑直接过滤 ObservableCollection。现在将 DataGrid 包装在 ScrollViewer 中可以解决问题。把我的头发拉了足够长的时间,所以我对你的回答很满意!! :)
    猜你喜欢
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多