WPF 8(WPF样式与资源)

WPF样式与资源

在控件中我们一般可以通过属性来设置它们的样式,如果我们要对很多控件用同一种样式。该怎么办能呢?

方法一:就是在每个控件的属性中该,显然这不是一种明智的选择。

那我们就用法二:

我们可以在他的父容器里的Style.Resource里设置。因为这样其他控件(在同一个父容器中)也可以访问到。

下面我用demo来讲解。

我们现在窗体上拖3个Button控件。我们在Window.Resources里设置它的Style

<Window.Resources>
        <Style x:Key="BtnStyle" TargetType="Button">
            <Setter Property="Background" Value="yellow"/>
        </Style>
    </Window.Resources>

这里要有TargetType用来识别绑定对象是什么。

接下来我们在Button上绑定Style

复制代码
<Grid>
        <Button Style="{StaticResource BtnStyle}" Content="Button" Height="43" HorizontalAlignment="Left" Margin="33,35,0,0" Name="button1" VerticalAlignment="Top" Width="88" />
        <Button Style="{StaticResource BtnStyle}" Content="Button" Height="43" HorizontalAlignment="Left" Margin="149,35,0,0" Name="button2" VerticalAlignment="Top" Width="85" />
        <Button Style="{StaticResource BtnStyle}" Content="Button" Height="43" HorizontalAlignment="Left" Margin="261,35,0,0" Name="button3" VerticalAlignment="Top" Width="84" />
    </Grid>
复制代码

其实就这个 Style="{StaticResource BtnStyle}"

效果图:

image

刚刚改变的是背景色,前景色呢?

我们只要加

<Setter Property="Foreground" Value="red"/>

如图:

image

若我们要给他些事件呢。比如鼠标移到Button上,会发生什么变化,按下去会发生什么变化。

这就要用到Style.Triggers

复制代码
<Window.Resources>
        <Style x:Key="BtnStyle" TargetType="Button">
            <Style.Triggers>
                <Trigger Property="Button.IsMouseOver" Value="True">
                    <Setter Property="Background" Value="lightBlue"/>
                </Trigger>
                <Trigger Property="Button.IsPressed" Value="True">
                    <Setter Property="Background" Value="Blue"/>
                </Trigger>
            </Style.Triggers>
            <Setter Property="Background" Value="yellow"/>
            <Setter Property="Foreground" Value="red"/>
        </Style>
    </Window.Resources>
复制代码

看到在原来插入的Style.Triggers了不。

效果图:

鼠标移过。

image 鼠标按下

image 因为两者颜色差不多 所以不太清楚的区别。

结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值