我如何可以滚动搜索的项目为GridView中的WPF的观点观点、项目、GridView、WPF

2023-09-05 04:03:21 作者:気貭ˉ小侽ゝ

作为参考this问题我想知道我怎么可以滚动搜索的项目进网格视图视图

As a reference to this question I want to know how can I scroll the searched item into the view of grid view

推荐答案

您可以创建一个 AttachedProperty 来跟踪 SelectedTtem ,如果需要滚动它进入视野。

You can create an AttachedProperty to keep track of the SelectedTtem and Scroll it into view if needed.

   // Using a DependencyProperty as the backing store for AutoScrollToSelectedRow.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AutoScrollToSelectedRowProperty =
        DependencyProperty.RegisterAttached("AutoScrollToSelectedRow", typeof(bool), typeof(DataGridTextSearch)
        , new UIPropertyMetadata(false, OnAutoScrollToSelectedRowChanged));

    public static bool GetAutoScrollToSelectedRow(DependencyObject obj)
    {
        return (bool)obj.GetValue(AutoScrollToSelectedRowProperty);
    }

    public static void SetAutoScrollToSelectedRow(DependencyObject obj, bool value)
    {
        obj.SetValue(AutoScrollToSelectedRowProperty, value);
    }

    public static void OnAutoScrollToSelectedRowChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
    {
        var datagrid = s as DataGrid;
        if (datagrid != null)
        {
            datagrid.IsSynchronizedWithCurrentItem = true;
            datagrid.EnableRowVirtualization = !((bool)e.NewValue);
            datagrid.SelectionChanged += (g, a) =>
            {
                if (datagrid.SelectedItem != null)
                {
                    datagrid.ScrollIntoView(datagrid.SelectedItem);
                }
            };
        }
    }

用法:

 <DataGrid local:DataGridTextSearch.AutoScrollToSelectedRow="True"