One of my WPF application was using a DataGrid and I needed to find out at a certain point of time whether the Scroll Bar (vertical or horizontal) is visible or not. If you ever run into scenario like this you can find this out using code given below.
In code snippet above 'dataGrid' is my DataGrid.
After running this piece of code in 'verticalBarVisibility' and 'horizontalBarVisibility' you will have the exact state of DataGrid's vertical and horizontal scroll bars.
1: ScrollViewer scrollViewer = FindVisualChild<ScrollViewer>(dataGrid);
2: Visibility verticalBarVisibility = scrollViewer.ComputedVerticalScrollBarVisibility;
3: Visibility horizontalBarVisibility = scrollViewer.ComputedHorizontalScrollBarVisibility;
1: private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
2: {
3: for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
4: {
5: DependencyObject child = VisualTreeHelper.GetChild(obj, i);
6: if (child != null && child is childItem)
7: return (childItem)child;
8: else
9: {
10: childItem childOfChild = FindVisualChild<childItem>(child);
11: if (childOfChild != null)
12: return childOfChild;
13: }
14: }
15: return null;
16: }
C# build scroll bar for DataGrid in .NET
ReplyDelete