您现在的位置是:首页 > 文章详情

WPF中Style文件的引用——使用xaml代码或者C#代码动态加载

日期:2018-08-13点击:320
原文: WPF中Style文件的引用——使用xaml代码或者C#代码动态加载

WPF中控件拥有很多依赖属性(Dependency Property),我们可以通过编写自定义Style文件来控制控件的外观和行为,如同CSS代码一般。
总结一下WPF中Style样式的引用方法:

一、内联样式

直接在控件的内部xaml代码中书写各种依赖属性,如下:

<Button Height="30" Width="60" Background="Green" Foreground="White"> </Button>

这种方式比较直接方便,适用于单个控件、代码量较少的Style设置,代码不能重用。

二、嵌入样式:

在窗体(Window)或者页面(Page)的资源节点下面(Window.Resources或者Page.Resources)添加Style代码,这样在整个窗体或者页面范围内可以实现Style代码重用。
第1步,书写Style代码:

<Window.Resources> <Style x:Key="myBtnStyle" TargetType="{x:Type Button}"> <Setter Property="Height" Value="72" /> <Setter Property="Width" Value="150" /> <Setter Property="Foreground" Value="Red" /> <Setter Property="Background" Value="Black" /> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="VerticalAlignment" Value="Top" /> </Style> </Window.Resources>

第2步,在Button的xaml代码中引用Style:

<Button Style="{StaticResource myBtnStyle}"></Button>

三、外联样式:

前面说的两种方式,都无法设置整个应用程式里面的全局Style,现在我们介绍全局设置Style的方式。
1.新建一个.xaml的资源文件,如/Theme/Style.xaml。
2.在该文件中编写样式代码:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib"> <Style x:Key="myBtnStyle" TargetType="Button"> <Setter Property="Height" Value="72" /> <Setter Property="Width" Value="150" /> <Setter Property="Foreground" Value="White" /> <Setter Property="Background" Value="Blue" /> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="VerticalAlignment" Value="Top" /> </Style> </ResourceDictionary>

3.在App.xaml文件中的<Applictaion.Resources>节点下添加<ResourceDictionary>节点:

<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/应用名称;component/Theme/Style.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>

这种方式相比前面两种使得样式和结构又更进一步分离了。在App.xaml引用,是全局的,可以使得一个样式可以在整个应用程序中能够复用。在普通页面中引用只能在当前页面上得到复用。

四、使用C#代码动态加载Style

1.假设应用程式用已经有了全局的资源文件(上面的方法中有介绍)。
2.编写C#代码:

Button btn =new Button(); btn.SetValue(Button.StyleProperty, Application.Current.Resources["资源名称"]);
原文链接:https://yq.aliyun.com/articles/677833
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章