WPF Listbox scroll down

10,314

You need to tell WPF where to start looking for the command handler. Without telling it, it will start looking from the Button and not find anything that handles the LineDownCommand. Unfortunately, setting it to the ListBox will not suffice because the ScrollViewer is inside the ListBox as part of its template, so WPF still won't find it.

Setting it to one of the ListBoxItems is naff, but works:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <ListBox x:Name="_listBox" ScrollViewer.VerticalScrollBarVisibility="Hidden">
            <ListBoxItem x:Name="_listBoxItem">One</ListBoxItem>
            <ListBoxItem>Two</ListBoxItem>
            <ListBoxItem>Three</ListBoxItem>
            <ListBoxItem>One</ListBoxItem>
            <ListBoxItem>Two</ListBoxItem>
            <ListBoxItem>Three</ListBoxItem>
            <ListBoxItem>One</ListBoxItem>
            <ListBoxItem>Two</ListBoxItem>
            <ListBoxItem>Three</ListBoxItem>
            <ListBoxItem>One</ListBoxItem>
            <ListBoxItem>Two</ListBoxItem>
            <ListBoxItem>Three</ListBoxItem>
        </ListBox>
        <Button Grid.Row="1" Command="ScrollBar.LineDownCommand" CommandTarget="{Binding ElementName=_listBoxItem}">Scroll Down</Button>
    </Grid>
</Window>

A better way to do this would be to either re-template the ListBox and stick the Button inside the template, or to wire up the CommandTarget in the code-behind.

Share:
10,314
Raven
Author by

Raven

https://github.com/AnderssonPeter

Updated on June 04, 2022

Comments

  • Raven
    Raven almost 2 years

    Lets say i have a listbox with many items so that a vertical scroll comes up, but i have hidden the scroll bar with

    ScrollViewer.VerticalScrollBarVisibility="Hidden"
    

    Is there any way i can add a button that would scroll down for me? iv tryed to add

    Command="ScrollBar.LineDownCommand" 
    

    to a button but that didnt have any effect.