wpf的样式与资源
程序员文章站
2022-07-13 23:03:39
...
wpf的样式与资源
1、样式:
样式由style属性设置,style属性通过setter元素改变,setter元素包括property和value属性,并给指定的属性设置一个指定的值;下面为一个简单的设置button控件样式的例子:
写法一:指定TargetType为Button;
<Button >
<Button.Style>
<Style TargetType="Button">
<Setter Property="Background" Value="red"/>
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="40"/>
</Style>
</Button.Style>
</Button>
写法二,style中不指定TargetType,在Property中的属性前加限制修饰;
<Button >
<Button.Style>
<Style>
<Setter Property="Button.Background" Value="red"/>
<Setter Property="Button.Width" Value="100"/>
<Setter Property="Button.Height" Value="40"/>
</Style>
</Button.Style>
</Button>
2、资源
以上控件的样式只能作用在该控件上,同一个窗体的其他控件是不能使用的,为了在同一个窗口中的其他控件也能使用此样式,就需要将此样式定义为资源,这样,在控件的style属性上通过引用资源的方式改变样式,示例如下:
在Window.Resources中定义资源定义资源时需要key,此key为资源的引用值,同样,TargetType可以不用提前写,在Property属性前加修饰即可,类似上面例子,
<Window.Resources>
<Style x:Key="buttonStyle" TargetType="{x:Type Button}">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0.0" Color="AliceBlue"/>
<GradientStop Offset="0.5" Color="Black"/>
<GradientStop Offset="0.9" Color="Red"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Width" Value="100"></Setter>
<Setter Property="Height" Value="50"></Setter>
</Style>
</Window.Resources>
定义好资源后就可以使用了,如下:
<Button Style="{StaticResource buttonStyle}"></Button>
StaticResource 为静态查找资源,即在编译的时候,后续细讲;
以上定义的资源在当前窗口的所有Button控件都可引用,但是程序中其他窗口的Button是不能使用的,为了统一与方便,将资源加到App.xaml文件中,就可实现整个程序的所以Button都可使用改资源所定义的样式了;如下:
<Application.Resources>
<Style x:Key="buttonStyle" TargetType="{x:Type Button}">
<Setter Property="Button.Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0.0" Color="AliceBlue"/>
<GradientStop Offset="0.5" Color="Black"/>
<GradientStop Offset="0.9" Color="Red"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Button.Width" Value="100"></Setter>
<Setter Property="Button.Height" Value="50"></Setter>
</Style>
</Application.Resources>
下一篇继续讲资源在代码中的访问及程序集之间的引用;
上一篇: WPF 遍历控件listview中的checkbox控件
下一篇: Button按钮样式风格模板