Tuesday, March 26, 2013

How do I change a control's style during run time?

Now this one actually took me a while to figure out. You can create Styles in XAML much like you can create a CSS class (see earlier post). Then you assign the control's Style property to a different Style by referring to its name. See below:

Simple Comparison 

HTML:

.MyButtonStyle {
    width: 250px;
    background-color: black;
    color: goldenrod;
}

In code-behind:
btnMyButton.CssClass = "MyButtonStyle";

XAML:

<Style x:Name="MyButtonStyle" TargetType="Button">
    <Setter Property="Width" Value="250" />
    <Setter Property="Background" Value="Black" />
    <Setter Property="Foreground" Value="Goldenrod" />
</Style>

In code-behind:
btnMyButton.Style = Resources["MyButtonStyle"] as Style;

Now you might have thought, "But why not just directly assign the style by name?" Like this:

btnSetStyle.Style = MyButtonStyle;

I'm not sure why this doesn't work. It compiles and runs just fine but the style of the button will NOT change. I'm not advanced enough to understand why one method works and the other doesn't. If you know feel free to add a comment. :)



No comments:

Post a Comment