C# 如何将搜索到的项目滚动到Wpf中的GridView视图中

C# 如何将搜索到的项目滚动到Wpf中的GridView视图中,c#,.net,wpf,C#,.net,Wpf,作为问题的参考,我想知道如何将搜索到的项目滚动到网格视图中您可以创建一个附件属性,以跟踪所选项目,并根据需要滚动到视图中 // Using a DependencyProperty as the backing store for AutoScrollToSelectedRow. This enables animation, styling, binding, etc... public static readonly DependencyProperty AutoScroll

作为问题的参考,我想知道如何将搜索到的项目滚动到网格视图中

您可以创建一个
附件属性
,以跟踪
所选项目
,并根据需要滚动到视图中

   // 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"

谢谢你的回复。我也尝试过类似的东西,但我不知道为什么这在我这边不起作用