控制ListBox滚动行为

时间:2012-04-24 22:25:57

标签: c# wpf xaml listbox scrollviewer

Adam Nathan的“WPF 4 Unleashed”第10章包含了控制ListBox滚动行为的XAML示例:

<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>

书中没有等效的C#示例。我做了一些研究,发现了一些迂回的方法来做到这一点。有两种适用于我的方法,请参阅this SO question。然而,这些方法看起来有点像hackish。在XAML中调整这些属性非常简单,但在C#中很难。

这只是WPF的一个区域,只能用于XAML而不是C#?任何人都可以解释XAML / C#之间在易用性方面的差异吗?这只是对WPF团队的监督吗?

1 个答案:

答案 0 :(得分:2)

你可以这样做。

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);