1

Chapter 10 of "WPF 4 Unleashed" by Adam Nathan includes this XAML example of controlling ListBox scrolling behaviour:

<Window x:Class="NathanControllingScrollingBehavior.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
             ScrollViewer.VerticalScrollBarVisibility="Disabled"
             ScrollViewer.CanContentScroll="False"
             ScrollViewer.IsDeferredScrollingEnabled="True">
        ...
    </ListBox>

</Window>

There isn't an equivalent C# example in the book. I did some research and found a few roundabout ways to do this. See this SO question for two approaches which worked for me. These approaches however, seem kind of hackish. Adjusting these properties is quite simple in XAML, but awkward from C#.

Is this simply an area of WPF which was meant to be used only from XAML and not C#? Can anyone explain the disparity in ease of use of these properties between XAML/C#? Is it just an oversight of the WPF team?

Community
  • 1
  • 1
dharmatech
  • 8,979
  • 8
  • 42
  • 88

1 Answers1

2

You can do it this way.

ListBox listBox1 = new ListBox();

listBox1.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty,
ScrollBarVisibility.Disabled);

listBox1.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, 
ScrollBarVisibility.Disabled);

listBox1.SetValue(ScrollViewer.CanContentScrollProperty, false);

listBox1.SetValue(ScrollViewer.IsDeferredScrollingEnabledProperty, true);
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208