【问题标题】:WPF: Dynamically changing the ScrollBarWidth in Code BehindWPF:在后面的代码中动态更改 ScrollBarWidth
【发布时间】:2023-04-02 09:36:01
【问题描述】:

如何从后面的代码中设置滚动条宽度?我在这篇文章 (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】:

    也许这种方法会帮助您: 它使用 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 - 接口

    【讨论】:

    • 我试过了,但我已将它放入 中,以便在我的应用程序中随处可用。尝试通过 访问它,但它不起作用。不可以绑定到 App 对象吗?
    • 也许这个链接会对你有所帮助:stackoverflow.com/questions/1389503/…
    猜你喜欢
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2013-12-14
    • 2012-05-30
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    相关资源
    最近更新 更多