将 ListBox 包装在另一个 ScrollViewer 中的解决方法允许以冗余 ScrollViewer 控件为代价的全 XAML 解决方案(请参阅问题中的评论)。最后,我的队友决定采用如下代码隐藏解决方案。
这是具有我们需要访问的 ScrollViewer 的 ListBox 的相关属性。
<ListBox Name="_listBox" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
Loaded="InitializeListBoxScrollViewerProperty"/>
这是公开滚动查看器以供外部控件使用的代码隐藏。
private static readonly DependencyPropertyKey ListBoxScrollViewerPropertyKey =
DependencyProperty.RegisterReadOnly("ListBoxScrollViewer", typeof(ScrollViewer),
typeof(MyEditView), new PropertyMetadata());
protected static readonly DependencyProperty ListBoxScrollViewerProperty =
ListBoxScrollViewerPropertyKey.DependencyProperty;
protected ScrollViewer ListBoxScrollViewer
{
get { return (ScrollViewer)GetValue(ListBoxScrollViewerProperty); }
private set { SetValue(ListBoxScrollViewerPropertyKey, value); }
}
private void InitializeListBoxScrollViewerProperty(object sender, RoutedEventArgs args)
{
if (ReferenceEquals(args.OriginalSource, _listBox))
{
var scrollViewer = _listBox.GetFirstDescendantBreadthFirst<ScrollViewer>();
if (scrollViewer != null)
{
ListBoxScrollViewer = scrollViewer;
}
}
}
以下是使用的扩展方法:
public static class DependencyObjectExtensions
{
public static TDescendant GetFirstDescendantBreadthFirst<TDescendant>
(this DependencyObject dependencyObject) where TDescendant : DependencyObject
{
if (dependencyObject == null) { throw new ArgumentNullException(); }
return GetFirstDescendantBreadthFirst<TDescendant>(GetAllChildren(dependencyObject));
}
private static TDescendant GetFirstDescendantBreadthFirst<TDescendant>
(IEnumerable<DependencyObject> descendants) where TDescendant : DependencyObject
{
if (!descendants.Any()) return null;
var descendant = descendants.OfType<TDescendant>().FirstOrDefault();
if (descendant != null) return descendant;
return GetFirstDescendantBreadthFirst<TDescendant>(descendants.SelectMany(GetAllChildren));
}
private static IEnumerable<DependencyObject> GetAllChildren(DependencyObject dependencyObject)
{
return Enumerable
.Range(0, VisualTreeHelper.GetChildrenCount(dependencyObject))
.Select(i => VisualTreeHelper.GetChild(dependencyObject, i));
}
}
最后,可以在 XAML 的另一部分访问滚动查看器。
<Grid>
<Grid.Style>
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding ListBoxScrollViewer.ComputedVerticalScrollBarVisibility,
RelativeSource={RelativeSource AncestorType=l:MyEditView}}" Value="Visible">
<Setter Property="Margin" Value="{StaticResource myWidenedMargin}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
</Grid>