WPF覆盖列表框中的ScrollVIewer

时间:2013-06-03 02:38:28

标签: c# wpf class override scrollview

我创建了一个名为“AniScrollViewer”的类,它可以设置垂直滚动偏移量
Scrollviewer代码隐藏动画。

public class AniScrollViewer : ScrollViewer {
    public static readonly DependencyProperty CurrentVerticalOffsetProperty =
        DependencyProperty.Register("CurrentVerticalOffset", typeof(double), typeof(AniScrollViewer),
        new PropertyMetadata(new PropertyChangedCallback(OnVerticalChanged)));

    public double CurrentVerticalOffset {
        get { return (double)GetValue(CurrentVerticalOffsetProperty); }
        set { SetValue(CurrentVerticalOffsetProperty, value); }
    }

    private static void OnVerticalChanged(DependencyObject property, DependencyPropertyChangedEventArgs e) {
        AniScrollViewer viewer = property as AniScrollViewer;
        viewer.ScrollToVerticalOffset((double)e.NewValue);
    }
}

我想将这个'AniScrollViewer'推送到列表框

我遇到了几个问题:

  • Listbox类里面已经有'scrollviewer'了。我想替换
    使用我的自定义AniScrollViewer的默认列表框scrollviewer,但我不知道如何执行此操作。
  • 我想在Listbox代码隐藏中获得ScrollViewer。像这样:

列表框列表框(已在XAML中定义)
AniScrollViewer scrollviewer = listbox。~~~~;

请帮忙。

1 个答案:

答案 0 :(得分:1)

  • 要使用自定义ScrollViewer替换默认Style,请为ListBox定义自定义ControlTemplate,并在ScrollViewer中切换默认local:AniScrollViewer你的(ListBox)。现在使用此Style的任何ScrollViewer都会有ControlTemplate。可以找到默认StyleScrollViewer Here
  • 要获得代码隐藏中的GetScrollViewer(DependencyObject o),您可以使用this作为参考。在功能

ScrollViewer

使用您的自定义if (o is AniScrollViewer) return o; 检查其类型是否安全,例如

ScrollViewer

<强>交替

但是在您的情况下,我不确定为什么您选择为此ListBox创建子类。可以尝试使用附加属性,而不是定义自己的ControlTemplate public class ScrollAnimator { public static readonly DependencyProperty ScrollToProperty = DependencyProperty.RegisterAttached( "ScrollTo", typeof(double), typeof(ScrollAnimator), new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.None, ScrollToChangedCallback)); private static void ScrollToChangedCallback( DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { ScrollViewer viewer = GetScrollViewer(dependencyObject) as ScrollViewer; if (viewer != null) viewer.ScrollToVerticalOffset((double)dependencyPropertyChangedEventArgs.NewValue); // Modify Above code to however you want to do the animation. } public static DependencyObject GetScrollViewer(DependencyObject o) { if (o is ScrollViewer) return o; for (int i = 0; i < VisualTreeHelper.GetChildrenCount(o); i++) { var child = VisualTreeHelper.GetChild(o, i); var result = GetScrollViewer(child); if (result == null) continue; return result; } return null; } public static void SetScrollTo(UIElement element, Orientation value) { element.SetValue(ScrollToProperty, value); } public static Orientation GetScrollTo(UIElement element) { return (Orientation)element.GetValue(ScrollToProperty); } } 时的麻烦。类似的东西:

<ListBox ItemsSource="{Binding Items}"
         local:ScrollAnimator.ScrollTo="{Binding ScrollTo}" />

和用法:

ControlTemplate

这样您就不需要定义自定义{{1}}以及随之而来的所有开销。