Search code examples
c#wpfxamlscrollpagedown

How do I move the scroll element in another UserControl with wpf?


How do I bind an element in another usercontrol to a command target?

This is main xaml

<Grid>
    <StackPanel>
        <Button Height="200" x:Name="PageUpButton" FontFamily="Marlett" FontSize="40" Content="5" Command="{x:Static ScrollBar.PageUpCommand}" CommandTarget="{Binding ElementName=scrollViewerActive}"/>
        <local:posMenuChild x:Name="PosMenuChild"/>
        <Button Height="200" x:Name="PageDownButton" FontFamily="Marlett"  FontSize="40" Content="6" Command="{x:Static ScrollBar.PageDownCommand}" CommandTarget="{Binding ElementName=ScrollViewerActive }"/>
    </StackPanel>        
</Grid>

What should I specify as CommandTarget? How do I scroll the element in the following UserControl with the Button in the top Window?

This is usercontrol

<Grid Height="200">
    <WrapPanel Orientation="Vertical"  Height="200">
        <ScrollViewer VerticalScrollBarVisibility="Hidden" Name="ScrollViewerActive" CanContentScroll="True" >
            <StackPanel>
                <TextBlock Text="Test1" FontSize="35"/>
                <TextBlock Text="Test2" FontSize="35"/>
                <TextBlock Text="Test3" FontSize="35"/>
                <TextBlock Text="Test4" FontSize="35"/>
                <TextBlock Text="Test5" FontSize="35"/>
                <TextBlock Text="Test6" FontSize="35"/>
            </StackPanel>
        </ScrollViewer>
    </WrapPanel>
</Grid>

Solution

  • Modify your usercontrol's code-behind with following:

    First, add a DependencyProperty to bind to of a ScrollViewer type

    public static readonly DependencyProperty ScrollTargetProperty = DependencyProperty.RegisterAttached(
            "ScrollTarget", typeof(ScrollViewer), typeof(UserControl1), new PropertyMetadata(null));
    
    public static void SetScrollTarget(DependencyObject element, ScrollViewer value)
    {
       element.SetValue(ScrollTargetProperty, value);
    }
    
    public static ScrollViewer GetScrollTarget(DependencyObject element)
    {
       return (ScrollViewer)element.GetValue(ScrollTargetProperty);
    }
    

    Don't forget to change UserControl1 to your usercontrol's class name.

    Then, set this property to ScrollViewerActive (i did it inside the control's constructor)

    SetScrollTarget(this, ScrollViewerActive);
    

    And now you can bind to it like this

    <Button Command="{x:Static ScrollBar.PageUpCommand}" CommandTarget="{Binding Path=ScrollTarget, ElementName=PosMenuChild, Mode=OneWay}"/>