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

上一章我们了解到了如何在页面或者App.xml文件中创建自定义样式,以及如何在页面文件中应用自定义的样式。本章将介绍如何在后台应用自定义样式,以及如何在后台自定义样式。

一、应用已有的自定义样式:

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

<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;

大家可以看到,按钮的背景色变成了红色。当然,根据不同的需求,在一个样式中可以添加多个Setter

关于简单样式的自定义和应用我们就介绍到这里,在以后的章节中,特别是在Chart的处理时我们需要更多的运用样式,

在后面的章节中我们会详细介绍更多与样式相关的知识。

  

 

 

posted on 2010-08-06 09:59  hades  阅读(2904)  评论(0编辑  收藏  举报

导航