您的位置:首页 > Web前端 > CSS

Silverlight Style 自定义样式在后台代码中应用

2013-06-20 21:05 239 查看
一、应用已有的自定义样式:

拿上一章我们自定义的样式举例:

<Application xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

x:Class="MyApp.App">

<Application.Resources>

<Style x:Name="MyTextBoxStyle" TargetType="TextBlock">

<Setter Property="FontSize" Value="10"></Setter>

<Setter…></Setter>

<Setter…></Setter>

</Style>

</Application.Resources>

</Application>

那么我们如何通过后台编码将这一样式应用到控件上呢?其实很简单,只需要一行代码即可:

textBlock.Style = Application.Current.Resources["MyTextBoxStyle"] as Style;

上面的样式是定义在App.xml中的全局样式,如果我们需要应用定义在页面中的样式,只需要稍作调整,代码如下:

textBlock.Style = Resources["MyTextBoxStyle"] as Style;

二、自定义样式:

了解了如何应用在页面文件中定义的样式,朋友们大概会问到,那么我们如何在后台直接定义样式呢?

下面我们就来介绍如何在后台自定义样式。

通过在学习如何在页面中定义样式,我们了解到,Silverlight的样式包含如下结构:

<Style x:Name="MyTextBoxStyle" TargetType="TextBlock">

<Setter Property="FontSize" Value="10"></Setter>

</Style>

所以,很显然,我们在后台定义样式也需要用到这两个对象,Style 和 Setter,下面是一段简短的示例代码:

System.Windows.Style btnStyle =new System.Windows.Style();
btnStyle.TargetType =typeof(System.Windows.Controls.Control);
Setter setterRed =new Setter(System.Windows.Controls.Control.BackgroundProperty, new SolidColorBrush(Colors.Red));
btnStyle.Setters.Add(setterRed);
this.btnClick.Style = btnStyle;


原文地址:/article/7010884.html

//如果silverlight 3.0可以采用
Uri uri = new Uri(" style1.xaml", UriKind.Relative);
ImplicitStyleManager.SetResourceDictionaryUri(control, uri);
ImplicitStyleManager.SetApplyMode(control, ImplicitStylesApplyMode.Auto);
ImplicitStyleManager.Apply(control);

//如果silverlight 4.0可以采用
Uri uri = new Uri(" style1.xaml", UriKind.Relative);
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri("/SilverlightTheme;component/"+uri, UriKind.Relative);
//Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(rd);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: