Silverlight:Change Button Background color


It is really hard when you want to remove the gradient effect in silverlight button control using designer mode.
I have struggled a lot to achieve this and finally I could solve this issue and thought of sharing this to every one.
By Default the if you try to create a button control and change the background color it look some thing like below

<Button x:Name=”btnTest” Content=”Default Background Color” Background=”Orange” Width=”170″ Height=”30″ HorizontalAlignment=”Left”>

I was expecting a orange color as the background of the button and I got in gradient effect..

So how do I get rid of this gradient effect.. The Below code resolve this issue

<Button Width=”100″ Height=”30″ Content=”Click Me !!!” Foreground=”White” >
<Button.Template>
<ControlTemplate TargetType=”Button”>
<Border x:Name=”Border” Background=”Orange”>
<ContentPresenter VerticalAlignment=”Center” HorizontalAlignment=”Center” />
</Border>
</ControlTemplate>
</Button.Template>
</Button>

and produces the following output.

Again if you want to customize some thing like rounded curve button you may need to add a attribute called CornerRadius.

<Button Width=”100″ Height=”30″ Content=”Click Me !!!” Foreground=”White” >
<Button.Template>
<ControlTemplate TargetType=”Button”>
<Border x:Name=”Border” Background=”Orange”
CornerRadius=”4″>
<ContentPresenter VerticalAlignment=”Center” HorizontalAlignment=”Center” />
</Border>
</ControlTemplate>
</Button.Template>
</Button>

and produces the following output.

Create button background from codebehind

StringBuilder sb = new StringBuilder();
sb.Append( "<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
sb.Append("xmlns:data='clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006' ");
sb.Append("TargetType='Button' >");
sb.Append("<Border x:Name=\"Border\" Background=\"Orange\" CornerRadius=\"4\"><ContentPresenter VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" /></Border> ");
sb.Append("</ControlTemplate> ");

Button btn = new Button();
btn.Width = width;
btn.Height = height;
btn.Content = content;
btn.Foreground = new SolidColorBrush(Colors.White);

ControlTemplate ct = XamlReader.Load(sb.ToString()) as ControlTemplate;
btn.Template = ct;
cnvParent.Children.Add(btn);

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

Advertisements