wpf 以编程方式修改样式中的属性

qltillow  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(114)

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

但我找不到这个样式对象中的正确属性。

另一个想法:

将width和height定义为DependencyProperties或实现INotifyPropertyChanged,但我认为在我的例子中,通过编程设置这两个值要容易得多。
对这个问题有什么看法或建议?

vq8itlhq

vq8itlhq1#

将此添加到您的资源:

<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"

相关问题