我创建了一个名为“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'推送到列表框
我遇到了几个问题:
列表框列表框(已在XAML中定义)
AniScrollViewer scrollviewer = listbox。~~~~;
请帮忙。
答案 0 :(得分:1)
ScrollViewer
替换默认Style
,请为ListBox
定义自定义ControlTemplate
,并在ScrollViewer
中切换默认local:AniScrollViewer
你的(ListBox
)。现在使用此Style
的任何ScrollViewer
都会有ControlTemplate
。可以找到默认Style
和ScrollViewer
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}}以及随之而来的所有开销。