C#样式的使用,添加自定义样式需对控件的属性相对熟悉,且需要对样式引用的格式熟悉(wpf对自定义样式中控件属性不给出提示,需自己写)。
下面是对StackPanel板式添加的自定义按钮样式
<!--样式-->
<Window x:Class="e2_19.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<!--布局Style-->
<Style x:Key="MyStyle1">
<Setter Property="StackPanel.Orientation" Value="Vertical"/>
<Setter Property="StackPanel.Background" Value="Gray"/>
<Setter Property="Button.FontSize" Value="9"/>
</Style>
<!--布局Style-->
<Style x:Key="MyStyle2">
<Setter Property="StackPanel.Orientation" Value="Horizontal"/>
<Setter Property="StackPanel.Background" Value="Black"/>
<!--<Setter Property="Button.FontSize" Value="15"/>-->
</Style>
<Style x:Key="BtnStyle">
<Style.Triggers><!--当鼠标掠过时触发Style-->
<Trigger Property="Button.IsMouseOver" Value="True">
<Setter Property="Button.Background" Value="Gray"/>
</Trigger>
</Style.Triggers>
<!--静态加载按钮样式-->
<Setter Property="Button.Width" Value="45"/>
<Setter Property="Button.Height" Value="45"/>
</Style>
<!--以上综合超级酷炫按钮样式-->
<!--可在计算器上使用-->
<Style x:Key="BtnDwonStyle">
<Style.Triggers>
<Trigger Property="Button.IsMouseOver" Value="True">
<Setter Property="Button.Background" Value="Gray"/>
</Trigger>
</Style.Triggers>
<Setter Property="Button.Foreground" Value="Yellow"/>
<Setter Property="Button.Width" Value="45"/>
<Setter Property="Button.Height" Value="45"/>
</Style>
</Window.Resources>
<!--样式使用-->
<StackPanel Width="200" Height="200" Name="RootStackPanel">
<StackPanel.Style>
<DynamicResource ResourceKey="MyStyle1"/>
</StackPanel.Style>
<Button Content="按钮1"/>
<Button>按钮2</Button>
<Button>按钮3</Button>
<Button>按钮4</Button>
<StackPanel>
<StackPanel.Style>
<DynamicResource ResourceKey="MyStyle2"/>
</StackPanel.Style>
<Button>Button55</Button>
<Button>Button66</Button>
<Button>Button77</Button>
</StackPanel>
<!--酷炫样式使用-->
<StackPanel>
<Button Name="Btn" Style="{StaticResource BtnStyle}" Content="B" Click="Button_Click"/>
</StackPanel>
</StackPanel>
</Window>
<!--炫酷样式的按钮后台响应-->
private void Button_Click(object sender, RoutedEventArgs e)
{
Btn.Style = (Style)(this.Resources["BtnDwonStyle"]);
}
本文介绍了在C#的WPF环境中如何创建和使用自定义样式,特别是针对StackPanel中的按钮控件。通过熟悉控件属性和样式引用格式,即使WPF不提供自定义样式中的属性提示,也能实现个性化的控件样式设计。

3452

被折叠的 条评论
为什么被折叠?



