手把手教你搭WPF架构之按钮的进阶设计学习

174 阅读2分钟

1 前言

在前面文章中介绍了按钮的简单设计到进阶设计,这次接着上次进阶设计来做进一步的介绍。


2 进阶设计

代码介绍:

<Window.Resources>
        <Style x:Key="CustomRadioButtonStyle" TargetType="RadioButton">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate  TargetType="RadioButton">
                        <Grid Background="Transparent" Height="50" Name="back">
                            <TextBlock Text="Click me!" FontSize="14" FontWeight="Bold" FontFamily="MV Boli"
                       HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsChecked" Value="True">
                                <Setter Property="Background" Value="#33FFFCC2" TargetName="back"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
  • Window.Resources——定义了窗口的资源字典,这里可以存放样式、数据模板等资源。新建项目中一般没有资源字典,需要自己在使用过程中进行手动添加。
  • Style——样式,可以根据自己使用的多类控件进行统一的样式定义,使得View界面设计达到一种统一的设计风。在使用过程中,常用TargetType搭配使用,TargetType的定义表示指定控件的样式。
  • SetterTemplate结合——设置样式的模板属性,Setter中还可以对背景、字体等多种属性进行定义设置。
  • ControlTemplate——自定义控件的外观和行为。这里是指定了 RadioButton 的外观和布局。
  • Grid——就是之前介绍过的网格,HorizontalAlignment="Center" VerticalAlignment="Center"表示水平和垂直对齐方式都设置为居中。
  • Triggers——定义了模板的触发器,触发器可以对一些事件做出设定,这里是对按下后的背景进行设置。

3 问题解决

介绍完style的设置,接着来解决上篇所提到的问题,我们使用的按钮都设定了统一的名称,不好区分使用。具体实现是我们在样式中采用了TextBlock控件,并统一命名为Text="Click me!" ,那么如何将统一的名称根据具体需要进行更改呢? 为了改变按钮的名称,我们可以这样做! image.png

代码如下:

<TextBlock Text="{TemplateBinding Content}" FontSize="14" FontWeight="Bold" FontFamily="MV Boli"
                       HorizontalAlignment="Center" VerticalAlignment="Center"/>
  • 模板绑定(TemplateBinding)——将控件的某个属性(如 Content)绑定到模板中的某个属性上(如 TextBlock.Text)。通过将style中的TextBlock.Text绑定Content,在RadioButton使用style时,我们可以单独设置Content,改变其设定值。

    代码如下:

<RadioButton Grid.Row="1"  GroupName="1" Content="1" Style="{StaticResource CustomRadioButtonStyle}"/>
<RadioButton Grid.Row="2"  GroupName="1" Content="2" Style="{StaticResource CustomRadioButtonStyle}"/>
<RadioButton Grid.Row="3"  GroupName="1" Content="3" Style="{StaticResource CustomRadioButtonStyle}"/>

具体效果如下:

image.png 我们将RadioButton的样式进行设置Style="{StaticResource CustomRadioButtonStyle}",然后单独将Content重新赋值,可以解决问题。 前提是需要把style中的TextBlock.Text与Content进行绑定!


总结

本文介绍了style的使用,并解决上一篇的遗留问题,对于采用模板绑定将需要的控件属性进行绑定就可以解决问题!