首页 > 解决方案 > WPF:在后面的代码中动态更改 ScrollBarWidth

问题描述

如何从后面的代码中设置滚动条宽度应用程序?我在这篇文章中找到了一些示例(如何在 WPF ScrollViewer 中增加滚动条宽度?),但仅在 XAML 中,而不是在动态中。

对我来说重要的是我能够在程序运行时更改滚动条的宽度。所以无论我做什么,都必须可以一遍又一遍地更新值。

<Style TargetType="{x:Type ScrollBar}">
<Setter Property="Stylus.IsFlicksEnabled" Value="True" />
<Style.Triggers>
    <Trigger Property="Orientation" Value="Horizontal">
        <Setter Property="Height" Value="40" />
        <Setter Property="MinHeight" Value="40" />
    </Trigger>
    <Trigger Property="Orientation" Value="Vertical">
        <Setter Property="Width" Value="40" />
        <Setter Property="MinWidth" Value="40" />
    </Trigger>
</Style.Triggers>

或者

<Application
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
>
<Application.Resources>
    <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">50</sys:Double>
    <sys:Double x:Key="{x:Static SystemParameters.HorizontalScrollBarHeightKey}">50</sys:Double>
</Application.Resources>

标签: c#wpfresourcesscrollbar

解决方案


也许这种方法会对您有所帮助:它使用 DataBinding(这应该是 WPF 中的方式)并为您提供更改代码隐藏宽度的机会。

XAML

<ScrollViewer>
        <ScrollViewer.Resources>
            <Style x:Key="{x:Type ScrollBar}" TargetType="{x:Type ScrollBar}">
                <Setter Property="Width" Value="{Binding MyWidth,Mode=OneWay}" />
            </Style>
        </ScrollViewer.Resources>
</ScrollViewer>

代码隐藏

    public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private double myWidth;
    public double MyWidth
    {
        get { return myWidth; }
        set 
        {
            if (value != this.myWidth)
            {
                myWidth = value; 
                NotifyPropertyChanged("MyWidth");
            }
        }
    }

    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = this;

        //set the width here in code behind
        this.MyWidth = 200;
    }

    protected virtual void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

不要忘记实现INotifyPropertyChanged- 接口


推荐阅读