问题
I have a DataGrid from the Silverligt 4.0 SDK. I want to access "HorizontalOffset" from the internal ScrollViewer of the DataGrid. I can access attached properties for it, such as:
<data:DataGrid x:Name="MyGrid"
ItemsSource="{Binding Elements}"
ScrollViewer.HorizontalScrollBarVisibility="Visible">
But how can I access the ScrollViewers HorizontalOffset property? If I could bind it in XAML it would be nice but it could be enough to access it from code behind.
I've tried to find it by iterating the visual tree from the DataGrid in code behind but I can't get hold of it (scroller is always null). I've tried several different implementations of FindVisualChild().
var scroller = MyGrid.FindVisualChild<ScrollViewer>();
回答1:
It might have something to do with the fact the the DataGrid
doesn't use a ScrollViewer
The default template manages its own scrolling and includes the two scroll bars. You therefore need to access the horizontal scroll bar.
I use my own VisualTreeEnumeration
class the code for which you'll find here.
var scrollBar = MyGrid.Descendents()
.OfType<ScrollBar>()
.FirstOrDefault(sb => sb.Name == "HorizontalScrollbar");
回答2:
Although your accepted answer states that DataGrid
does not use a ScrollViewer
it appears the first visual child of a DataGrid
is a Border
that has a ScrollViewer
as its child. So you can get at the ScrollViewer
using something like:
let border = Media.VisualTreeHelper.GetChild(grid, 0) :?> Controls.Border
let scroll = border.Child :?> Controls.ScrollViewer
来源:https://stackoverflow.com/questions/4876620/access-horizontaloffset-from-scrollviewer-in-datagrid