C# 重置WPF数据网格滚动条位置
将Datagrid的.DataContext属性更改为新源时,所选项目将被清除,但滚动条位置将保留。为了避免这种情况,我在更改datacontext后调用.ScrollIntoView(.Item(0))向上移动滚动条。但它会在几分之一秒内显示错误的页面,当我在更改datacontext之前滚动到顶部时,我也遇到了同样的问题 那么我怎样才能同时更改.DataContext和重置滚动条的位置呢 编辑:我应该提到我的XAML如下所示:C# 重置WPF数据网格滚动条位置,c#,wpf,datagrid,scrollbar,C#,Wpf,Datagrid,Scrollbar,将Datagrid的.DataContext属性更改为新源时,所选项目将被清除,但滚动条位置将保留。为了避免这种情况,我在更改datacontext后调用.ScrollIntoView(.Item(0))向上移动滚动条。但它会在几分之一秒内显示错误的页面,当我在更改datacontext之前滚动到顶部时,我也遇到了同样的问题 那么我怎样才能同时更改.DataContext和重置滚动条的位置呢 编辑:我应该提到我的XAML如下所示: <DataGrid VirtualizingStackPa
<DataGrid VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">
因此,虚拟化可能是原因。您是否尝试在DataContextChanged事件中调用
ScrollToTop
以查看ScrollViewer
<DataGrid VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling"
DataContextChanged="dataGrid_DataContextChanged"
...>
private void dataGrid_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
ScrollViewer scrollViewer = GetVisualChild<ScrollViewer>(dataGrid);
if (scrollViewer != null)
{
scrollViewer.ScrollToTop();
}
}
私有void dataGrid_DataContextChanged(对象发送方,DependencyPropertyChangedEventArgs e)
{
ScrollViewer ScrollViewer=GetVisualChild(dataGrid);
如果(scrollViewer!=null)
{
scrollViewer.ScrollToTop();
}
}
GetVisualChild
private static T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
private static T GetVisualChild(DependencyObject父对象),其中T:Visual
{
T child=默认值(T);
int numVisuals=VisualTreeHelper.GetChildrenCount(父级);
对于(int i=0;i