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

Modify Properties inside a Style programmatically

我在 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>

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

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

通过资源访问样式:

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"