WPF:动态更改后面代码中的ScrollBarWidth

时间:2019-03-30 19:05:20

标签: c# wpf resources scrollbar

如何从后面的代码中将滚动条宽度应用程序设置为较宽?我在这篇文章(How to increase scrollbar width in 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>

1 个答案:

答案 0 :(得分:0)

也许这种方法将帮助您: 它使用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-界面