mola
mola

Reputation: 1150

How to toggle scroll lock in a WPF ListView?

How to toggle scroll lock in a WPF ListView?

When more items are added to a ListView, than there is space to show the following should happen depending of the scroll lock state.

  1. When scroll lock is enabled the ListView should not scroll when adding more items (this is the default behavior).

  2. When scroll lock is disabled the ListView should automatically scroll to the bottom so the newly added items are visible to the user.

The scroll lock state should be controlled by the (seldom used) 'scroll lock' button on a typical keyboard.

EDIT: A bit of code...

<ListView x:Name="logMessagesListView" ItemsSource="{Binding ElementName=self, Path=LogMessages}">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="Created" Width="100" DisplayMemberBinding="{Binding Created}"/>
                <GridViewColumn Header="Level" Width="80" DisplayMemberBinding="{Binding LogLevel}"/>
                <GridViewColumn Header="Message" Width="350" DisplayMemberBinding="{Binding Message}"/>
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

Upvotes: 0

Views: 1051

Answers (2)

ShadeOfGrey
ShadeOfGrey

Reputation: 1266

I would keep the log messages in an ObservableCollection, both for automatic UI notifications and the CollectionChanged event. Once a new item is added, check if the button is clicked. If it is, move to the last item (or you can use the index/item properties of the event arguments).

You're going to need to add System.Windows.Forms to the project references so you can check the button state.

public partial class MainWindow : Window
{
    private ObservableCollection<LogMessage> logMessages;

    public MainWindow()
    {
        this.logMessages = new ObservableCollection<LogMessage>();

        /* add/load some data */

        this.logMessages.CollectionChanged += new NotifyCollectionChangedEventHandler(this.LogMessages_CollectionChanged);

        this.LogMessages = CollectionViewSource.GetDefaultView(this.logMessages);

        InitializeComponent();
    }

    public ICollectionView LogMessages
    {
        get;
        set;
    }

    private void LogMessages_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            if (System.Windows.Forms.Control.IsKeyLocked(System.Windows.Forms.Keys.Scroll))
            {
                this.LogMessages.MoveCurrentToLast();
            }
        }
    }
}

public class LogMessage
{
    public string Created
    { get; set; }

    public string LogLevel
    { get; set; }

    public string Message
    { get; set; }
}

Upvotes: 1

Tom Kerkhove
Tom Kerkhove

Reputation: 2191

Put ScrollViewer.CanContentScroll="False" in your XAML and that should work!

Upvotes: 0

Related Questions