Windows Phone 7 cs页面添加样式

对于控件的样式一般都是在xaml页面进行赋值的,不过有时候在一些特殊环境下,比如动态生成控件,那么这时候就是需要在cs页面上给控件添加样式了。

第一种方法:

现在App.xaml页面上把样式添加上为全局资源

<Application.Resources>
        ……
</Application.Resources>

然后再其他cs页面通过下面的代码来赋值样式

Style mystyle = Application.Current.Resources[styleName] as Style;

Button bt = new Button();

bt.Style = mystyle;

第二种方法:

直接在cs页面写样式的代码

如:

var style = new Style();
style.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Red)));
style.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Blue)));
var styleCopy = new Style();

foreach (var setter in style.Setters)
{
   var typedSetter = setter as Setter;
   if (typedSetter != null)
   {
     var newSetter = new Setter(typedSetter.Property, typedSetter.Value);
     styleCopy.Setters.Add(newSetter);
   }
}

原文地址:https://www.cnblogs.com/linzheng/p/2341851.html