gpt4 book ai didi

c# - 以编程方式修改样式内的属性

转载 作者:太空宇宙 更新时间:2023-11-03 22:49:12 26 4
gpt4 key购买 nike

我在 UserControl 的资源中定义了以下样式:

<Style x:Key="MenuItemButton" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Width="40" Height="40" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="1,1,1,1" CornerRadius="3">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Button.Foreground" Value="#666666" />
<Setter Property="Button.Background" Value="Transparent" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Button.Cursor" Value="Hand" />
<Setter Property="Button.Foreground" Value="White" />
<Setter Property="Button.Background" Value="#666666" />
</Trigger>
</Style.Triggers>
</Style>

例如我像下面这样使用它:

<Button Click="Toolbar_DocumentMarkup_Click" Name="BtnUnderline" Margin="10,0,0,0" Style="{StaticResource MenuItemButton}">
<fa:FontAwesome VerticalAlignment="Center" Icon="Underline" FontSize="24"/>
</Button>

我需要从后面的代码中以编程方式设置边框的宽度和高度,以便在运行时更新 View 。

到目前为止我尝试了什么:

通过资源访问样式:

var style = Resources["MenuItemButton"] as Style

但我无法在此样式对象中找到正确的属性。

另一个想法:

将宽度和高度定义为 DependencyProperties 或实现 INotifyPropertyChanged,但我认为在我的情况下,以编程方式设置这两个值要容易得多。

对这个问题有什么意见或建议?

最佳答案

将此添加到您的资源中:

 <sys:Double x:Key="ButtonHeight">200</sys:Double>
<sys:Double x:Key="ButtonWidth">200</sys:Double>

<Style x:Key="MenuItemButton" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Width="40" Height="40" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="1,1,1,1" CornerRadius="3">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Height" Value="{DynamicResource ButtonHeight}" />
<Setter Property="Width" Value="{DynamicResource ButtonWidth}" />
<Setter Property="Button.Foreground" Value="#666666" />
<Setter Property="Button.Background" Value="Transparent" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Button.Cursor" Value="Hand" />
<Setter Property="Button.Foreground" Value="White" />
<Setter Property="Button.Background" Value="#666666" />
</Trigger>
</Style.Triggers>

然后在您后面的代码中使用以下方法在您的事件中更改它:

this.Resources["ButtonHeight"] = ...

this.Resources["ButtonWidth"] = ...

编辑:忘了你当然需要添加系统路径

xmlns:sys="clr-namespace:System;assembly=mscorlib"

关于c# - 以编程方式修改样式内的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48318107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com