一、应用已有的自定义样式:
拿上一章我们自定义的样式举例:
<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>
</ Style
Application.Resources Application >
那么我们如何通过后台编码将这一样式应用到控件上呢?其实很简单,只需要一行代码即可:
textBlock.Style = Application.Current.Resources["MyTextBoxStyle"] as Style;
上面的样式是定义在App.xml中的全局样式,如果我们需要应用定义在页面中的样式,只需要稍作调整,代码如下:
textBlock.Style = Resources["MyTextBoxStyle"] as Style;
二、自定义样式:
了解了如何应用在页面文件中定义的样式,朋友们大概会问到,那么我们如何在后台直接定义样式呢?
通过在学习如何在页面中定义样式,我们了解到,Silverlight的样式包含如下结构:
<Style x:Name=" targettype>
Setter Property Value></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;
原文地址: http://www.cnblogs.com/HighFun/archive/2012/01/27/2330223.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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。