WPF:动态更改Code Behind中的ScrollBarWidth

问题描述 投票:0回答:1

如何从代码后面设置滚动条宽度应用程序?我在这篇文章中发现了一些例子(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>

c# wpf resources scrollbar
1个回答
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 - 接口

© www.soinside.com 2019 - 2024. All rights reserved.