[SOLVED] How to catch ScrollViewer ScrollChanged event ?

Please post public support tickets here. Note: for private support tickets, please send an email to support@cshtml5.com instead.
Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

[SOLVED] How to catch ScrollViewer ScrollChanged event ?

Postby Sesztak » Wed Sep 28, 2016 1:46 am

Dear JS-Support,

Background info: we have two ScrollViewers and we would like to sync the scroll position of both for each other:
e.g. two ScrollViewers vertically (one on the other top), when the bottom's scrollbar dragged (scrolled) by the user we would like to set (sync) the scrollbar's of top ScrollViewer.

Question: How to catch ScrollViewer ScrollChanged event ?
(normally in WPF there is a ScrollChanged event, but in present state of CSHTML v9.4 beta no such an event !)

Thanks for your kind reply,
Best Regards,
Péter

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: How to catch ScrollViewer ScrollChanged event ?

Postby JS-Support @Userware » Wed Sep 28, 2016 2:19 am

Hi,

Here is a method that lets you attach to the "Scroll" event:

Code: Select all

public static void ListenToScrollEvent(ScrollViewer scrollViewer, Action handler)
{
    if (scrollViewer.IsLoaded)
    {
        var div = CSHTML5.Interop.GetDiv(scrollViewer);
        CSHTML5.Interop.ExecuteJavaScript(@"
var div = $0;
var handler = $1;
div.addEventListener('scroll', handler, false);
", div, handler);
    }
    else
    {
        System.Windows.MessageBox.Show("You must add the ScrollViewer to the visual tree before listening to the Scroll event. For example, call this method from the Page.Loaded event instead.");
    }
}



Here is how to test it:
- Put the static method above somewhere in your code
- Define a ScrollViewer in XAML like so:

Code: Select all

<ScrollViewer x:Name="ScrollViewer1" Height="100" Width="20">
    <Rectangle Height="300" Width="20"/>
</ScrollViewer>

- Call the following C# code:

Code: Select all

public MainPage()
{
    this.InitializeComponent();

    this.Loaded += MainPage_Loaded;
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    ListenToScrollEvent(ScrollViewer1, () =>
    {
        System.Windows.MessageBox.Show("Scrolled!");
    });
}


You can adapt the code or use similar Interop calls to get the scroll position etc.

Regards,
JS-Support

Sesztak
Posts: 172
Joined: Fri Jun 24, 2016 2:19 am

Re: How to catch ScrollViewer ScrollChanged event ?

Postby Sesztak » Wed Sep 28, 2016 2:40 am

Great thanks, I will check it soon.
br,
Péter


Return to “Technical Support”

Who is online

Users browsing this forum: No registered users and 3 guests