Okay guys, I have been scratching my head like mad over this issue and have spent a good few hours trying to research how it works but I am yet to find an answer, if you wish to see any of my SRC feel free to ask about it and I will see if I can help.
Basically the issue I am having is that I have a TreeView of folders in my application i.e.:
Catalog
Brands
Nike
Adidas
Lactose
Styles
Sandles
Trainers
Boots
The issue that I am trying to fix is that when I drag a folder around (This is handled in my DragDropManager class), I am unable to scroll up or down(simply displays a lovely stop sign). I am also unable to find a scroller actually within the TreeView, so I am unsure how it is being generated (This is not my own software, I have recently started working for a company so I am not familiar with the code and no one else seems to know.)
This is a problem if I want to move something from the very top to the very bottom.
The scrolling works fine on its own without the dragging being done.
If anyone wishes to see any part of my code feel free to ask as I am unsure what to actually show you guys.
I have read through a good few articles and am just left scratching my head.
I have created an attached property for achieving this behavior, have a look at my post here -
Attached Behavior for auto scrolling containers while doing Drag & Drop
Main logic is something like this -
private static void OnContainerPreviewDragOver(object sender, DragEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (container == null) { return; }
ScrollViewer scrollViewer = GetFirstVisualChild<ScrollViewer>(container);
if (scrollViewer == null) { return; }
double tolerance = 60;
double verticalPos = e.GetPosition(container).Y;
double offset = 20;
if (verticalPos < tolerance) // Top of visible list?
{
//Scroll up
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - offset);
}
else if (verticalPos > container.ActualHeight - tolerance) //Bottom of visible list?
{
//Scroll down
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + offset);
}
}
Similar questions on SO (although they are mostly for ListBox/ListView but should work for TreeView too) -
WPF Listbox auto scroll while dragging
WPF ListView Databound Drag/Drop Auto Scroll
WPF Drag-to-scroll doesn't work correctly
I know this question really old, but here is the MVVM way as attached property:
using System.Windows;
using System.Windows.Controls;
namespace AndroidCtrlUI.XTools.Behaviors
{
///<summary>
/// TreeItemAttach
///<para/> TreeViewItem
///</summary>
public sealed class TreeItemAttach
{
#region BringIntoView
///<summary>
/// DependencyProperty
///</summary>
public static readonly DependencyProperty BringIntoViewProperty = DependencyProperty.RegisterAttached("BringIntoView", typeof(bool), typeof(TreeItemAttach), new UIPropertyMetadata(false, (s, e) =>
{
if ((bool)e.NewValue != (bool)e.OldValue && s is TreeViewItem t)
{
if ((bool)e.NewValue)
{
t.Selected += BringIntoView;
}
else
{
t.Selected -= BringIntoView;
}
}
}));
///<summary>
/// Get
///</summary>
///<param name="target">DependencyObject</param>
///<returns>ICommand</returns>
public static bool GetBringIntoView(DependencyObject target)
{
return (bool)target.GetValue(BringIntoViewProperty);
}
///<summary>
/// Set
///</summary>
///<param name="target">DependencyObject</param>
///<param name="value">ICommand</param>
public static void SetBringIntoView(DependencyObject target, bool value)
{
target.SetValue(BringIntoViewProperty, value);
}
private static void BringIntoView(object sender, RoutedEventArgs e)
{
if (e.Source is TreeViewItem s)
{
double h = s.ActualHeight;
if (s.IsExpanded && s.Items.Count > 0)
{
h = s.ActualHeight / TreeWalker(s);
}
s.BringIntoView(new Rect(0, h * -1, s.ActualWidth, h * 2.5));
}
}
private static long TreeWalker(TreeViewItem item)
{
long c = item.Items.Count;
foreach (object i in item.Items)
{
if (i != null && item.ItemContainerGenerator.ContainerFromItem(i) is TreeViewItem t && t.IsExpanded && t.Items.Count > 0)
{
c += TreeWalker(t);
}
}
return c;
}
#endregion
}
}
And it can be used like:
<Style x:Key="TreeViewItemStyle" TargetType="{x:Type TreeViewItem}">
<Setter Property="tool:TreeItemAttach.BringIntoView" Value="True"/>
</Style>
Related
In one of the latest releases Xamarin.Forms added the possibility to place the toolbar at the bottom (ToolBarPlacement) and by setting the Property BarBackgroundColor on NavigationPage the background color of the toolbar can be changed.
Unfortunately, when the toolbar is split (as is the default on Windows 10 Mobile or when ToolbarPlacement is bottom) both bars have the same background color.
In my app I want to achieve that the top bar (with title and hamburger menu) has the system's accent color and the bottom bar (with commands and flyout) is gray, as this combination is also used by many system apps (e.g. Mail or Calendar on Windows 10 Mobile).
But I cannot figure out how to do it without touching the core implementation in Xamarin.Forms. I already tried custom NavigationPageRenderer and custom PageRenderer, but many of the relevant fields are private, sealed or internal or are accessing internal interfaces.
The background colors of the two bars seem to be bound to the same property as changing the background of one bar in Visual Studio's Live XAML Tree View also changes the color of the other one.
Any help on how to achieve the desired look will be appreciated.
Finally, I achieved the desired result.
One of the problems was that my RootPage was a MasterDetailPage, so I had to create a MasterDetailPageRenderer. Also I assumed that Xamarin would use the actual UWP Page's TopAppBar and BottomAppBar properties. This is not the case.
With the following MasterDetailPageRenderer the top bar (with hamburger menu button and title) is tinted green while the bottom bar stays the default gray (basically the renderer just removes the Background binding of the StackPanel representing the top bar and sets it to Green). One problem was, that the FindName and FindByName methods were not working (always returned null), so I had to roll my own implementations using the VisualTreeHelper.
[assembly: ExportRenderer(typeof(MasterDetailPage), typeof(CustomMasterDetailPageRender))]
public class CustomMasterDetailPageRender : MasterDetailPageRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<MasterDetailPage> e)
{
base.OnElementChanged(e);
if (Element != null)
{
Element.Appearing += Element_Appearing;
}
}
private void Element_Appearing(object sender, EventArgs e)
{
(sender as MasterDetailPage).Appearing -= Element_Appearing;
if (Control != null)
{
var topBarArea = FindElementByName(Control, "TopCommandBarArea");
if (topBarArea != null)
{
var topContent = FindElementByType<StackPanel>(topBarArea);
if (topContent != null)
{
topContent.Background = new SolidColorBrush(Colors.Green);
}
}
}
}
static DependencyObject FindElementByName(DependencyObject parent, string name)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var sub = VisualTreeHelper.GetChild(parent, i);
if (sub is FrameworkElement)
{
if (((FrameworkElement)sub).Name == name)
{
return sub;
}
}
var r = FindElementByName(sub, name);
if (r != null)
return r;
}
return null;
}
static T FindElementByType<T>(DependencyObject parent)
where T: DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var sub = VisualTreeHelper.GetChild(parent, i);
if (sub is T)
{
return (T)sub;
}
var r = FindElementByType<T>(sub);
if (r != null)
return r;
}
return null;
}
}
Is there a way to smoothly animate a ScrollViewers vertical offset in Windows Phone 8.1 Runtime?
I have tried using the ScrollViewer.ChangeView() method and the change of vertical offset is not animated no matter if I set the disableAnimation parameter to true or false.
For example: myScrollViewer.ChangeView(null, myScrollViewer.VerticalOffset + p, null, false);
The offset is changed without animation.
I also tried using a vertical offset mediator:
/// <summary>
/// Mediator that forwards Offset property changes on to a ScrollViewer
/// instance to enable the animation of Horizontal/VerticalOffset.
/// </summary>
public sealed class ScrollViewerOffsetMediator : FrameworkElement
{
/// <summary>
/// ScrollViewer instance to forward Offset changes on to.
/// </summary>
public ScrollViewer ScrollViewer
{
get { return (ScrollViewer)GetValue(ScrollViewerProperty); }
set { SetValue(ScrollViewerProperty, value); }
}
public static readonly DependencyProperty ScrollViewerProperty =
DependencyProperty.Register("ScrollViewer",
typeof(ScrollViewer),
typeof(ScrollViewerOffsetMediator),
new PropertyMetadata(null, OnScrollViewerChanged));
private static void OnScrollViewerChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var mediator = (ScrollViewerOffsetMediator)o;
var scrollViewer = (ScrollViewer)(e.NewValue);
if (null != scrollViewer)
{
scrollViewer.ScrollToVerticalOffset(mediator.VerticalOffset);
}
}
/// <summary>
/// VerticalOffset property to forward to the ScrollViewer.
/// </summary>
public double VerticalOffset
{
get { return (double)GetValue(VerticalOffsetProperty); }
set { SetValue(VerticalOffsetProperty, value); }
}
public static readonly DependencyProperty VerticalOffsetProperty =
DependencyProperty.Register("VerticalOffset",
typeof(double),
typeof(ScrollViewerOffsetMediator),
new PropertyMetadata(0.0, OnVerticalOffsetChanged));
public static void OnVerticalOffsetChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var mediator = (ScrollViewerOffsetMediator)o;
if (null != mediator.ScrollViewer)
{
mediator.ScrollViewer.ScrollToVerticalOffset((double)(e.NewValue));
}
}
/// <summary>
/// Multiplier for ScrollableHeight property to forward to the ScrollViewer.
/// </summary>
/// <remarks>
/// 0.0 means "scrolled to top"; 1.0 means "scrolled to bottom".
/// </remarks>
public double ScrollableHeightMultiplier
{
get { return (double)GetValue(ScrollableHeightMultiplierProperty); }
set { SetValue(ScrollableHeightMultiplierProperty, value); }
}
public static readonly DependencyProperty ScrollableHeightMultiplierProperty =
DependencyProperty.Register("ScrollableHeightMultiplier",
typeof(double),
typeof(ScrollViewerOffsetMediator),
new PropertyMetadata(0.0, OnScrollableHeightMultiplierChanged));
public static void OnScrollableHeightMultiplierChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var mediator = (ScrollViewerOffsetMediator)o;
var scrollViewer = mediator.ScrollViewer;
if (null != scrollViewer)
{
scrollViewer.ScrollToVerticalOffset((double)(e.NewValue) * scrollViewer.ScrollableHeight);
}
}
}
and I can animate the VerticalOffset property with DoubleAnimation:
Storyboard sb = new Storyboard();
DoubleAnimation da = new DoubleAnimation();
da.EnableDependentAnimation = true;
da.From = Mediator.ScrollViewer.VerticalOffset;
da.To = da.From + p;
da.Duration = new Duration(TimeSpan.FromMilliseconds(300));
da.EasingFunction = new ExponentialEase() { EasingMode = EasingMode.EaseOut };
Storyboard.SetTarget(da, Mediator);
Storyboard.SetTargetProperty(da, "(Mediator.VerticalOffset)");
sb.Children.Add(da);
sb.Begin();
Mediator is declared in XAML.
But this animation is not smooth on my device (Lumia 930).
You should stick with ChangeView for scrolling animations regardless of whether data virtualization is on or not.
Without seeing your code where the ChangeView doesn't work, it's a bit hard to guess what's really going on but there are a couple of things that you can try.
First approach is to add a Task.Delay(1) before calling ChangeView, just to give the OS some time to finish off other concurrent UI tasks.
await Task.Delay(1);
scrollViewer.ChangeView(null, scrollViewer.ScrollableHeight, null, false);
The second approach is a bit more complex. What I've noticed is that, when you have many complex items in the ListView, the scrolling animation from the first item to the last (from the ChangeView method) isn't very smooth at all.
This is because the ListView first needs to realize/render many items along the way due to data virtualization and then does the animated scrolling. Not very efficient IMHO.
What I came up with is this - First, use a non-animated ListView.ScrollIntoView to scroll to the last item just to get it realized. Then, call ChangeView to move the offset up to a size of the ActualHeight * 2 of the ListView with animation disabled (you can change it to whatever size you want based on your app's scrolling experience). Finally, call ChangeView again to scroll back to the end, with animation this time. Doing this will give a much better scrolling experience 'cause the scrolling distance is just the ActualHeight of the ListView.
Keep in mind that when the item you want to scroll to is already realized on the UI, you don't want to do anything above. You simply just calculate the distance between this item and the top of the ScrollViewer and call ChangeView to scroll to it.
I already wrapped the logic above in this answer's Update 2 section (thanks to this question I realized my initial answer doesn't work when virtualization is on :p). Let me know how you go.
I think that question has already been answered here:
Animated (Smooth) scrolling on ScrollViewer
There is also the WinRT XAML Toolki, which provides "a way to scroll a ScrollViewer to specified offset with animation":
http://winrtxamltoolkit.codeplex.com/
With ScrollToVerticalOffset deprecated/obsolete in newer builds of Windows 10 (leaving the ScrollViewOffSetMediator extension control no longer working), and the new ChangeView method not actually providing smooth or controllable animation, a new solution is needed. Please see my answer here which allows one to smoothly animate and zoom the ScrollViewer and its contents to any desired position, regardless of where the application's end user has the scrollbars initially positioned:
How to scroll to element in UWP
I believe this article is what you're looking for and it seems the method he used is working for you.
Quick Way:
Add offset dependency parameter manually to scrollviewer.
Duplicate your scrollviewer
Use an animator.
I have gone through the thread:
binding two VerticalScrollBars one to another
it has almost helped to achieve the goal but still there is something missing. It is that moving the scrollbars left-right or up-down gives expected behavior of scrolling in both of my scrollviewers but when we try to scroll using/clicking arrow buttons at the ends of these scrollbars in scrollviewers only one scrollviewer is scrolled which is not the expected behavior.
So what else we need to add/edit to solve this?
One way to do this is using the ScrollChanged event to update the other ScrollViewer
<ScrollViewer Name="sv1" Height="100"
HorizontalScrollBarVisibility="Auto"
ScrollChanged="ScrollChanged">
<Grid Height="1000" Width="1000" Background="Green" />
</ScrollViewer>
<ScrollViewer Name="sv2" Height="100"
HorizontalScrollBarVisibility="Auto"
ScrollChanged="ScrollChanged">
<Grid Height="1000" Width="1000" Background="Blue" />
</ScrollViewer>
private void ScrollChanged(object sender, ScrollChangedEventArgs e)
{
if (sender == sv1)
{
sv2.ScrollToVerticalOffset(e.VerticalOffset);
sv2.ScrollToHorizontalOffset(e.HorizontalOffset);
}
else
{
sv1.ScrollToVerticalOffset(e.VerticalOffset);
sv1.ScrollToHorizontalOffset(e.HorizontalOffset);
}
}
The question is for WPF, but in case anyone developing UWP stumbles upon this, I had to take a slightly different approach.
In UWP, when you set the scroll offset of the other scroll viewer (using ScrollViewer.ChangeView), it also triggers the ViewChanged event on the other scroll viewer, basically creating a loop, causing it to be very stuttery, and not work properly.
I resolved this by using a little time-out on handling the event, if the object being scrolled is not equal to the last object that handled the event.
XAML:
<ScrollViewer x:Name="ScrollViewer1" ViewChanged="SynchronizedScrollerOnViewChanged"> ... </ScrollViewer>
<ScrollViewer x:Name="ScrollViewer2" ViewChanged="SynchronizedScrollerOnViewChanged"> ... </ScrollViewer>
Code behind:
public sealed partial class MainPage
{
private const int ScrollLoopbackTimeout = 500;
private object _lastScrollingElement;
private int _lastScrollChange = Environment.TickCount;
public SongMixerUserControl()
{
InitializeComponent();
}
private void SynchronizedScrollerOnViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
if (_lastScrollingElement != sender && Environment.TickCount - _lastScrollChange < ScrollLoopbackTimeout) return;
_lastScrollingElement = sender;
_lastScrollChange = Environment.TickCount;
ScrollViewer sourceScrollViewer;
ScrollViewer targetScrollViewer;
if (sender == ScrollViewer1)
{
sourceScrollViewer = ScrollViewer1;
targetScrollViewer = ScrollViewer2;
}
else
{
sourceScrollViewer = ScrollViewer2;
targetScrollViewer = ScrollViewer1;
}
targetScrollViewer.ChangeView(null, sourceScrollViewer.VerticalOffset, null);
}
}
Note that the timeout is 500ms. This may seem a little long, but as UWP apps have an animation (or, easing, really) in their scrolling (when using the scroll wheel on a mouse), it causes the event to trigger for a few times within a few hundred milliseconds. This timeout seems to work perfectly.
If it can be useful, here's a behavior (for UWP, but it's enough to get the idea); using a behavior helps to decouple view and code in a MVVM design.
using Microsoft.Xaml.Interactivity;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
public class SynchronizeHorizontalOffsetBehavior : Behavior<ScrollViewer>
{
public static ScrollViewer GetSource(DependencyObject obj)
{
return (ScrollViewer)obj.GetValue(SourceProperty);
}
public static void SetSource(DependencyObject obj, ScrollViewer value)
{
obj.SetValue(SourceProperty, value);
}
// Using a DependencyProperty as the backing store for Source. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SourceProperty =
DependencyProperty.RegisterAttached("Source", typeof(object), typeof(SynchronizeHorizontalOffsetBehavior), new PropertyMetadata(null, SourceChangedCallBack));
private static void SourceChangedCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SynchronizeHorizontalOffsetBehavior synchronizeHorizontalOffsetBehavior = d as SynchronizeHorizontalOffsetBehavior;
if (synchronizeHorizontalOffsetBehavior != null)
{
var oldSourceScrollViewer = e.OldValue as ScrollViewer;
var newSourceScrollViewer = e.NewValue as ScrollViewer;
if (oldSourceScrollViewer != null)
{
oldSourceScrollViewer.ViewChanged -= synchronizeHorizontalOffsetBehavior.SourceScrollViewer_ViewChanged;
}
if (newSourceScrollViewer != null)
{
newSourceScrollViewer.ViewChanged += synchronizeHorizontalOffsetBehavior.SourceScrollViewer_ViewChanged;
synchronizeHorizontalOffsetBehavior.UpdateTargetViewAccordingToSource(newSourceScrollViewer);
}
}
}
private void SourceScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
ScrollViewer sourceScrollViewer = sender as ScrollViewer;
this.UpdateTargetViewAccordingToSource(sourceScrollViewer);
}
private void UpdateTargetViewAccordingToSource(ScrollViewer sourceScrollViewer)
{
if (sourceScrollViewer != null)
{
if (this.AssociatedObject != null)
{
this.AssociatedObject.ChangeView(sourceScrollViewer.HorizontalOffset, null, null);
}
}
}
protected override void OnAttached()
{
base.OnAttached();
var source = GetSource(this.AssociatedObject);
this.UpdateTargetViewAccordingToSource(source);
}
}
Here's how to use it:
<ScrollViewer
HorizontalScrollMode="Enabled"
HorizontalScrollBarVisibility="Hidden"
>
<interactivity:Interaction.Behaviors>
<behaviors:SynchronizeHorizontalOffsetBehavior Source="{Binding ElementName=ScrollViewer}" />
</interactivity:Interaction.Behaviors>
</ScrollViewer>
<ScrollViewer x:Name="ScrollViewer" />
Well, I made an implementation based on https://www.codeproject.com/Articles/39244/Scroll-Synchronization but it's I think neater.
There's a synchronised scroll token that holds references to the things to scroll.
Then there's the attached property that is separate.
I haven't figured out how to unregister because the reference remains - so I left that unimplemented.
Eh, here goes:
public class SynchronisedScroll
{
public static SynchronisedScrollToken GetToken(ScrollViewer obj)
{
return (SynchronisedScrollToken)obj.GetValue(TokenProperty);
}
public static void SetToken(ScrollViewer obj, SynchronisedScrollToken value)
{
obj.SetValue(TokenProperty, value);
}
public static readonly DependencyProperty TokenProperty =
DependencyProperty.RegisterAttached("Token", typeof(SynchronisedScrollToken), typeof(SynchronisedScroll), new PropertyMetadata(TokenChanged));
private static void TokenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var scroll = d as ScrollViewer;
var oldToken = e.OldValue as SynchronisedScrollToken;
var newToken = e.NewValue as SynchronisedScrollToken;
if (scroll != null)
{
oldToken?.unregister(scroll);
newToken?.register(scroll);
}
}
}
and the other bit
public class SynchronisedScrollToken
{
List<ScrollViewer> registeredScrolls = new List<ScrollViewer>();
internal void unregister(ScrollViewer scroll)
{
throw new NotImplementedException();
}
internal void register(ScrollViewer scroll)
{
scroll.ScrollChanged += ScrollChanged;
registeredScrolls.Add(scroll);
}
private void ScrollChanged(object sender, ScrollChangedEventArgs e)
{
var sendingScroll = sender as ScrollViewer;
foreach (var potentialScroll in registeredScrolls)
{
if (potentialScroll == sendingScroll)
continue;
if (potentialScroll.VerticalOffset != sendingScroll.VerticalOffset)
potentialScroll.ScrollToVerticalOffset(sendingScroll.VerticalOffset);
if (potentialScroll.HorizontalOffset != sendingScroll.HorizontalOffset)
potentialScroll.ScrollToHorizontalOffset(sendingScroll.HorizontalOffset);
}
}
}
Use by defining a token in some resource accessible to all the things that need to be scroll synchronised.
<blah:SynchronisedScrollToken x:Key="scrollToken" />
And then use it wherever you need it by:
<ListView.Resources>
<Style TargetType="ScrollViewer">
<Setter Property="blah:SynchronisedScroll.Token"
Value="{StaticResource scrollToken}" />
</Style>
</ListView.Resources>
I've only tested it when scrolling vertically and it works for me.
In following up on Rene Sackers code listing in C# for UWP, here is how I addressed this same issue in VB.Net for UWP with a timeout to avoid the staggering effect because of one Scroll Viewer Object firing the event because it's view was changed by the code and not by user interaction. I put a 500 Millisecond timeout period which works well for my application.
Notes: svLvMain is a scrollviewer (for me it is the main window)
svLVMainHeader is a scrollviewer (for me it is the header that goes above the main window and is what I want to track along with the main window and vice versa).
Zooming or scrolling either scrollviewer will keep both scrollviewers in sync.
Private Enum ScrollViewTrackingMasterSv
Header = 1
ListView = 2
None = 0
End Enum
Private ScrollViewTrackingMaster As ScrollViewTrackingMasterSv
Private DispatchTimerForSvTracking As DispatcherTimer
Private Sub DispatchTimerForSvTrackingSub(sender As Object, e As Object)
ScrollViewTrackingMaster = ScrollViewTrackingMasterSv.None
DispatchTimerForSvTracking.Stop()
End Sub
Private Sub svLvTracking(sender As Object, e As ScrollViewerViewChangedEventArgs, ByRef inMastScrollViewer As ScrollViewer)
Dim tempHorOffset As Double
Dim tempVerOffset As Double
Dim tempZoomFactor As Single
Dim tempSvMaster As New ScrollViewer
Dim tempSvSlave As New ScrollViewer
Select Case inMastScrollViewer.Name
Case svLvMainHeader.Name
Select Case ScrollViewTrackingMaster
Case ScrollViewTrackingMasterSv.Header
tempSvMaster = svLvMainHeader
tempSvSlave = svLvMain
tempHorOffset = tempSvMaster.HorizontalOffset
tempVerOffset = tempSvMaster.VerticalOffset
tempZoomFactor = tempSvMaster.ZoomFactor
tempSvSlave.ChangeView(tempHorOffset, tempVerOffset, tempZoomFactor)
If DispatchTimerForSvTracking.IsEnabled Then
DispatchTimerForSvTracking.Stop()
DispatchTimerForSvTracking.Start()
End If
Case ScrollViewTrackingMasterSv.ListView
Case ScrollViewTrackingMasterSv.None
tempSvMaster = svLvMainHeader
tempSvSlave = svLvMain
ScrollViewTrackingMaster = ScrollViewTrackingMasterSv.Header
DispatchTimerForSvTracking = New DispatcherTimer()
AddHandler DispatchTimerForSvTracking.Tick, AddressOf DispatchTimerForSvTrackingSub
DispatchTimerForSvTracking.Interval = New TimeSpan(0, 0, 0, 0, 500)
DispatchTimerForSvTracking.Start()
tempHorOffset = tempSvMaster.HorizontalOffset
tempVerOffset = tempSvMaster.VerticalOffset
tempZoomFactor = tempSvMaster.ZoomFactor
tempSvSlave.ChangeView(tempHorOffset, tempVerOffset, tempZoomFactor)
End Select
Case svLvMain.Name
Select Case ScrollViewTrackingMaster
Case ScrollViewTrackingMasterSv.Header
Case ScrollViewTrackingMasterSv.ListView
tempSvMaster = svLvMain
tempSvSlave = svLvMainHeader
tempHorOffset = tempSvMaster.HorizontalOffset
tempVerOffset = tempSvMaster.VerticalOffset
tempZoomFactor = tempSvMaster.ZoomFactor
tempSvSlave.ChangeView(tempHorOffset, tempVerOffset, tempZoomFactor)
If DispatchTimerForSvTracking.IsEnabled Then
DispatchTimerForSvTracking.Stop()
DispatchTimerForSvTracking.Start()
End If
Case ScrollViewTrackingMasterSv.None
tempSvMaster = svLvMain
tempSvSlave = svLvMainHeader
ScrollViewTrackingMaster = ScrollViewTrackingMasterSv.ListView
DispatchTimerForSvTracking = New DispatcherTimer()
AddHandler DispatchTimerForSvTracking.Tick, AddressOf DispatchTimerForSvTrackingSub
DispatchTimerForSvTracking.Interval = New TimeSpan(0, 0, 0, 0, 500)
DispatchTimerForSvTracking.Start()
tempHorOffset = tempSvMaster.HorizontalOffset
tempVerOffset = tempSvMaster.VerticalOffset
tempZoomFactor = tempSvMaster.ZoomFactor
tempSvSlave.ChangeView(tempHorOffset, tempVerOffset, tempZoomFactor)
End Select
Case Else
Exit Sub
End Select
End Sub
Private Sub svLvMainHeader_ViewChanged(sender As Object, e As ScrollViewerViewChangedEventArgs) Handles svLvMainHeader.ViewChanged
Call svLvTracking(sender, e, svLvMainHeader)
End Sub
Private Sub svLvMain_ViewChanged(sender As Object, e As ScrollViewerViewChangedEventArgs) Handles svLvMain.ViewChanged
Call svLvTracking(sender, e, svLvMain)
End Sub
My goal is to create a reusable Attached Behavior for a FlowDocumentScrollViewer, so that the viewer automaticly scrolls to the end whenever the FlowDocument has been updated (appended).
Problems so far:
OnEnabledChanged gets called before the visual tree is completed, and thus doesn't find the ScrollViewer
I don't know how to attach to the DependencyProperty containing the FlowDocument. My plan was to use it's changed event to initialize the ManagedRange property. (Manually triggered for the first time if needed.)
I don't know how to get to the ScrollViewer property from within the range_Changed method, as it doesn't have the DependencyObject.
I realize that those are potentially 3 separate issues (aka. questions). However they are dependent on each other and the overall design I've attempted for this behavior. I'm asking this as a single question in case I'm going about this the wrong way. If I am, what is the right way?
/// Attached Dependency Properties not shown here:
/// bool Enabled
/// DependencyProperty DocumentProperty
/// TextRange MonitoredRange
/// ScrollViewer ScrollViewer
public static void OnEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d == null || System.ComponentModel.DesignerProperties.GetIsInDesignMode(d))
return;
DependencyProperty documentProperty = null;
ScrollViewer scrollViewer = null;
if (e.NewValue is bool && (bool)e.NewValue)
{
// Using reflection so that this will work with similar types.
FieldInfo documentFieldInfo = d.GetType().GetFields().FirstOrDefault((m) => m.Name == "DocumentProperty");
documentProperty = documentFieldInfo.GetValue(d) as DependencyProperty;
// doesn't work. the visual tree hasn't been built yet
scrollViewer = FindScrollViewer(d);
}
if (documentProperty != d.GetValue(DocumentPropertyProperty) as DependencyProperty)
d.SetValue(DocumentPropertyProperty, documentProperty);
if (scrollViewer != d.GetValue(ScrollViewerProperty) as ScrollViewer)
d.SetValue(ScrollViewerProperty, scrollViewer);
}
private static ScrollViewer FindScrollViewer(DependencyObject obj)
{
do
{
if (VisualTreeHelper.GetChildrenCount(obj) > 0)
obj = VisualTreeHelper.GetChild(obj as Visual, 0);
else
return null;
}
while (!(obj is ScrollViewer));
return obj as ScrollViewer;
}
public static void OnDocumentPropertyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue != null)
{
DependencyProperty dp = e.OldValue as DependencyProperty;
// -= OnFlowDocumentChanged
}
if (e.NewValue != null)
{
DependencyProperty dp = e.NewValue as DependencyProperty;
// += OnFlowDocumentChanged
// dp.AddOwner(typeof(AutoScrollBehavior), new PropertyMetadata(OnFlowDocumentChanged));
// System.ArgumentException was unhandled by user code Message='AutoScrollBehavior'
// type must derive from DependencyObject.
}
}
public static void OnFlowDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextRange range = null;
if (e.NewValue != null)
{
FlowDocument doc = e.NewValue as FlowDocument;
if (doc != null)
range = new TextRange(doc.ContentStart, doc.ContentEnd);
}
if (range != d.GetValue(MonitoredRangeProperty) as TextRange)
d.SetValue(MonitoredRangeProperty, range);
}
public static void OnMonitoredRangeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue != null)
{
TextRange range = e.OldValue as TextRange;
if (range != null)
range.Changed -= new EventHandler(range_Changed);
}
if (e.NewValue != null)
{
TextRange range = e.NewValue as TextRange;
if (range != null)
range.Changed -= new EventHandler(range_Changed);
}
}
static void range_Changed(object sender, EventArgs e)
{
// need ScrollViewer!!
}
OnEnabledChanged gets called before
the visual tree is completed, and thus
doesn't find the ScrollViewer
Use Dispatcher.BeginInvoke to enqueue the rest of the work to happen asynchronously, after the visual tree is built. You will also need to call ApplyTemplate to ensure that the template has been instantiated:
d.Dispatcher.BeginInvoke(new Action(() =>
{
((FrameworkElement)d).ApplyTemplate();
d.SetValue(ScrollViewerProperty, FindScrollViewer(d));
}));
Note that you don't need to check whether the new value is different from the old one. The framework handles that for you when setting dependency properties.
You could also use FrameworkTemplate.FindName to get the ScrollViewer from the FlowDocumentScrollViewer. FlowDocumentScrollViewer has a named template part of type ScrollViewer called PART_ContentHost that is where it will actually host the content. This can be more accurate in case the viewer is re-templated and has more than one ScrollViewer as a child.
var control = d as Control;
if (control != null)
{
control.Dispatcher.BeginInvoke(new Action(() =>
{
control.ApplyTemplate();
control.SetValue(ScrollViewerProperty,
control.Template.FindName("PART_ContentHost", control)
as ScrollViewer);
}));
}
I don't know how to attach to the
DependencyProperty containing the
FlowDocument. My plan was to use it's
changed event to initialize the
ManagedRange property. (Manually
triggered for the first time if
needed.)
There is no way built into the framework to get property changed notification from an arbitrary dependency property. However, you can create your own DependencyProperty and just bind it to the one you want to watch. See Change Notification for Dependency Properties for more information.
Create a dependency property:
private static readonly DependencyProperty InternalDocumentProperty =
DependencyProperty.RegisterAttached(
"InternalDocument",
typeof(FlowDocument),
typeof(YourType),
new PropertyMetadata(OnFlowDocumentChanged));
And replace your reflection code in OnEnabledChanged with simply:
BindingOperations.SetBinding(d, InternalDocumentProperty,
new Binding("Document") { Source = d });
When the Document property of the FlowDocumentScrollViewer changes, the binding will update InternalDocument, and OnFlowDocumentChanged will be called.
I don't know how to get to the
ScrollViewer property from within the
range_Changed method, as it doesn't
have the DependencyObject.
The sender property will be a TextRange, so you could use ((TextRange)sender).Start.Parent to get a DependencyObject and then walk up the visual tree.
An easier method would be to use a lambda expression to capture the d variable in OnMonitoredRangeChanged by doing something like this:
range.Changed += (sender, args) => range_Changed(d);
And then creating an overload of range_Changed that takes in a DependencyObject. That will make it a little harder to remove the handler when you're done, though.
Also, although the answer to Detect FlowDocument Change and Scroll says that TextRange.Changed will work, I didn't see it actually fire when I tested it. If it doesn't work for you and you're willing to use reflection, there is a TextContainer.Changed event that does seem to fire:
var container = doc.GetType().GetProperty("TextContainer",
BindingFlags.Instance | BindingFlags.NonPublic).GetValue(doc, null);
var changedEvent = container.GetType().GetEvent("Changed",
BindingFlags.Instance | BindingFlags.NonPublic);
EventHandler handler = range_Changed;
var typedHandler = Delegate.CreateDelegate(changedEvent.EventHandlerType,
handler.Target, handler.Method);
changedEvent.GetAddMethod(true).Invoke(container, new object[] { typedHandler });
The sender parameter will be the TextContainer, and you can use reflection again to get back to the FlowDocument:
var document = sender.GetType().GetProperty("Parent",
BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(sender, null) as FlowDocument;
var viewer = document.Parent;
Does this help?
It's a good start at least (maybe?).
Is it possible to programmatically scroll a WPF listview? I know winforms doesn't do it, right?
I am talking about say scrolling 50 units up or down, etc. Not scrolling an entire item height at once.
Yes, you'll have to grab the ScrollViwer from the ListView, or but once you have access to that, you can use the methods exposed by it or override the scrolling. You can also scroll by getting the main content area and using it's implementation of the IScrollInfo interface.
Here's a little helper to get the ScrollViwer component of something like a ListBox, ListView, etc.
public static DependencyObject GetScrollViewer(DependencyObject o)
{
// Return the DependencyObject if it is a ScrollViewer
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;
}
else
{
return result;
}
}
return null;
}
And then you can just use .LineUp() and .LineDown() like this:
private void OnScrollUp(object sender, RoutedEventArgs e)
{
var scrollViwer = GetScrollViewer(uiListView) as ScrollViewer;
if (scrollViwer != null)
{
// Logical Scrolling by Item
// scrollViwer.LineUp();
// Physical Scrolling by Offset
scrollViwer.ScrollToVerticalOffset(scrollViwer.VerticalOffset + 3);
}
}
private void OnScrollDown(object sender, RoutedEventArgs e)
{
var scrollViwer = GetScrollViewer(uiListView) as ScrollViewer;
if (scrollViwer != null)
{
// Logical Scrolling by Item
// scrollViwer.LineDown();
// Physical Scrolling by Offset
scrollViwer.ScrollToVerticalOffset(scrollViwer.VerticalOffset + 3);
}
}
<DockPanel>
<Button DockPanel.Dock="Top"
Content="Scroll Up"
Click="OnScrollUp" />
<Button DockPanel.Dock="Bottom"
Content="Scroll Down"
Click="OnScrollDown" />
<ListView x:Name="uiListView">
<!-- Content -->
</ListView>
</DockPanel>
The Logical scrolling exposed by LineUp and LineDown do still scroll by item, if you want to scroll by a set amount you should use the ScrollToHorizontal/VerticalOffset that I've used above. If you want some more complex scrolling too, then take a look at the answer I've provided in this other question.
Have you tried ScrollIntoView?
Alternatively, if it's not a specific item you brought into view, but an offset from the current position, you can use BringIntoView.