Skip to main content

Microsoft Silverlight

Answered Question Changing a button's style in runtime ?RSS Feed

(0)

nosuic
nosuic

Member

Member

515 points

133 Posts

Changing a button's style in runtime ?

In XAML I have 2 styles for buttons (in UserControl.Resources tag) and 1 button. The first style is already applied to my button and what i want now is to change its style (to the second one) when it's clicked. I was trying the following with no luck:

 

         private void onClick(object sender, RoutedEventArgs e)
        {
            Button bt = sender as Button;

            bt.Style = (Style)FindName("activated"); // 1st way

            //bt.SetValue(Button.StyleProperty, FindName("activated")); 2nd way
        } 
 

activated is the name of the second style.

  i've been thinking that it might not be possible, i've tried so many ways..do you have any ideas? what am i doing wrong ?

 thanks a lot in advance! 8-)

sladapter
sladapter

All-Star

All-Star

17441 points

3,172 Posts

Re: Changing a button's style in runtime ?

 If you want to set the style defined in the UserControl.Resources you do this:

 bt.Style = (Style)this.Resources["activated"];
But you can only do this (apply style to a control) once in code.  
 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

nosuic
nosuic

Member

Member

515 points

133 Posts

Re: Changing a button's style in runtime ?

I get again the same error "Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))"

sladapter:
But you can only do this (apply style to a control) once in code.

Trying to change a button's style on runtime, when this button has already a style, might be the second time the code is trying to apply a style to it.

So it's not possible actually..

Thanks for helping :)

sladapter
sladapter

All-Star

All-Star

17441 points

3,172 Posts

Answered Question

Re: Changing a button's style in runtime ?

That might be the case.

Another way to dynamically change a style is to change the Style definition itself.  You can dynamically import the style xaml and set the this.Resources["buttonStyle"] = XamlReader.Load(newStyleXamlString) as Style. This way you do not reset control's style, but control will take the new style because you changed style definition.

see this blog:

http://leeontech.wordpress.com/2008/07/21/dynamic-styles/

and this thread:

http://silverlight.net/forums/p/21371/74796.aspx#74796

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

nosuic
nosuic

Member

Member

515 points

133 Posts

Re: Changing a button's style in runtime ?

 Actually, changing the style itself was my first idea, but I found it too complicated. The fact that the trick with 2 styles isn't working leaves no choice which way to follow.

Thanks very much for the links, i never thought that somebody would like to change a style on runtime until I checked those links ;-P

Thanks again! :)

sladapter
sladapter

All-Star

All-Star

17441 points

3,172 Posts

Re: Changing a button's style in runtime ?

Actually, for your purpose, using ToggleButton and define Checked state might be a simpler approach than define 2 styles for Button.

See this thread:

http://silverlight.net/forums/t/24461.aspx

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

nosuic
nosuic

Member

Member

515 points

133 Posts

Re: Changing a button's style in runtime ?

 that's correct.. it's a big deal to follow the best way and use the right controls from the begining of a project...

codism
codism

Member

Member

372 points

121 Posts

Re: Changing a button's style in runtime ?

I just want to throw an idea here: if a control's style cannot be assigned twice, there may be a work around: just take the old control out and create a new control and add it to the parent control. Putting the new control in the old control's place may be a little tricky but should be doable.

microsoft_kc
microsof...

Contributor

Contributor

2890 points

564 Posts

Re: Changing a button's style in runtime ?

Use the following:  

bt.Style = (Style)this.Resources["activated"];
 

Remember: Please click on "Mark As Answer", if this answered your query partially or fully.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog

davjanks
davjanks

Member

Member

8 points

6 Posts

Re: Changing a button's style in runtime ?

Hi I know this is quite a while later but...

 I have tried the code sample above and it does not set my style at runtime. Here is my code

Button newButton = new Button()

{

Content = itemDescription,

HorizontalAlignment =
HorizontalAlignment.Left,Style = (Style)Resources["redButton"]

};

One difference is that my style is in the app.xaml not local resource. Any ideas?

sladapter
sladapter

All-Star

All-Star

17441 points

3,172 Posts

Re: Changing a button's style in runtime ?

 If the style is defined in App.xmal, use 

Style = Application.Current.Resources["redButton"] as Style;

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

egoZd
egoZd

Member

Member

326 points

125 Posts

Re: Changing a button's style in runtime ?

Please view this post to find out how to dymatic set up style for button

 http://www.slblogger.cn/p60.htm

Something remember ,Something forgot!


www.douziwang.cn

(My Silverlight Blog Jet,Silverlight game ect.)

davjanks
davjanks

Member

Member

8 points

6 Posts

Re: Changing a button's style in runtime ?

Thanks sladapter

Worked like a charm.

HarjinderSingh9988
Harjinde...

Member

Member

12 points

41 Posts

Re: Changing a button's style in runtime ?

Hi Sladapter,

 I tried as u said that picking up style from external xml file. i created a file consisting of style that I assign to a button at runtime which is already having a style defined in xaml.  my styl file is as follows   . I am getting error when I use gradient color or storyboard Present in Mouse over, pressed etc,i am also unable to chnge the content If the content is already assigned in the xaml file. i am using web service to read my style file.

<!--<?xml version="1.0" encoding="utf-8" ?>-->.

<Style xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

 

x:Key="stylebtnallclick" TargetType="Button">

<Setter Property="FontSize" Value="10"/>

<!--<Setter Property="Background" Value="#FF1F3B53"/>-->

<Setter Property="Foreground" Value="Red"/>

<Setter Property="Padding" Value="3"/>

<Setter Property="Content" Value="Hello"/>

<Setter Property="ContentTemplate" Value="Hello"/><Setter Property="BorderThickness" Value="1"/>

 

<Setter Property="BorderBrush">

<Setter.Value>

<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

<GradientStop Color="#FFA3AEB9" Offset="0"/>

<GradientStop Color="#FF8399A9" Offset="0.375"/>

<GradientStop Color="#FF718597" Offset="0.375"/>

<GradientStop Color="#FF617584" Offset="1"/>

</LinearGradientBrush>

</Setter.Value>

</Setter>

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="Button">

<Grid>

<VisualStateManager.VisualStateGroups>

<VisualStateGroup x:Name="CommonStates">

<VisualState x:Name="Normal"/>

<VisualState x:Name="MouseOver"><!--<Storyboard>

<DoubleAnimationUsingKeyFrames Storyboard.TargetName="BackgroundAnimation" Storyboard.TargetProperty="Opacity">

<SplineDoubleKeyFrame KeyTime="0" Value="1"/>

</DoubleAnimationUsingKeyFrames>

<ColorAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)">

<SplineColorKeyFrame KeyTime="0" Value="#7FFFFFFF"/>

</ColorAnimationUsingKeyFrames>

</Storyboard>
-->

</VisualState>

<VisualState x:Name="Pressed"><!--<Storyboard>

<DoubleAnimationUsingKeyFrames Storyboard.TargetName="BackgroundAnimation" Storyboard.TargetProperty="Opacity">

<SplineDoubleKeyFrame KeyTime="0" Value="1"/>

</DoubleAnimationUsingKeyFrames>

<ColorAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Color)">

<SplineColorKeyFrame KeyTime="0" Value="#D8FFFFFF"/>

</ColorAnimationUsingKeyFrames>

<ColorAnimationUsingKeyFrames Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)">

<SplineColorKeyFrame KeyTime="0" Value="#3FFFFFFF"/>

</ColorAnimationUsingKeyFrames>

</Storyboard>
-->

</VisualState>

<VisualState x:Name="Disabled"><!--<Storyboard>

<DoubleAnimationUsingKeyFrames Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="Opacity">

<SplineDoubleKeyFrame KeyTime="0" Value=".55"/>

</DoubleAnimationUsingKeyFrames>

</Storyboard>
-->

</VisualState>

</VisualStateGroup>

<VisualStateGroup x:Name="FocusStates">

<VisualState x:Name="Focused"><!--<Storyboard>

<DoubleAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity">

<SplineDoubleKeyFrame KeyTime="0" Value="1"/>

</DoubleAnimationUsingKeyFrames>

</Storyboard>
-->

</VisualState>

<VisualState x:Name="Unfocused"/>

</VisualStateGroup>

</VisualStateManager.VisualStateGroups>

<Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">

<Grid Margin="1" Background="{TemplateBinding Background}" Opacity="0.25">

<Border x:Name="BackgroundAnimation" Background="#FF62E4FF"/>

<Rectangle x:Name="BackgroundGradient" Fill="#FF62E4FF">

 

</
Rectangle>

</Grid>

</Border>

<ContentPresenter x:Name="contentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="0,0,0,1"/>

<Rectangle x:Name="DisabledVisualElement" Fill="#FFFFFFFF" RadiusX="0" RadiusY="0" IsHitTestVisible="false" Opacity="0"/>

<Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="0" RadiusX="0" RadiusY="0" Margin="1" IsHitTestVisible="false" Opacity="0"/>

</Grid>

</ControlTemplate>

</Setter.Value></Setter>

 

 

</Style>


My Web service code is as follows.....

public XmlDocument GetStyle(String Filename)
        {
            String st = Server.MapPath("Styles/" + Filename + ".xml");
             if (File.Exists(Server.MapPath("Styles/" + Filename + ".xml")))

                       {
                            XmlDocument xmlDoc = new XmlDocument();

                            xmlDoc.Load(Server.MapPath("Styles/" + Filename + ".xml"));

    

                            return xmlDoc;
 
                       }

                           else

                          return null;
        }



and I called this method in my silverlight application as......

 void btnShowAllConvos_Click(object sender, RoutedEventArgs e)
        {
            Button btnRef = null;
            try
            {
                btnRef = e.OriginalSource as Button;
                if (btnRef != null)
                {
                    // btnRef.Background = new SolidColorBrush(Colors.Blue);
                  //  objJakayaServices.GetStyleDocumentAsync("MyStyles.xml");
                    objstyle.GetStyleAsync("MyStyles");
                    objstyle.GetStyleCompleted += new EventHandler(objstyle_GetStyleCompleted);


                }
                CurrentConvoType = ConvoType.All;
                objJakayaServices.GetLoggedUsersConvoListAsync(this.UserName, CurrentConvoStatus, CurrentConvoType, this.CurrentTimeSpan);
            }
            catch (Exception ex) { }
            finally
            {
                btnRef = null;
            }
        }


        void objstyle_GetStyleCompleted(object sender, JakayaConvo.MyTestStyleService.GetStyleCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null && e.Result != null)
                {
                    Style dynamicstyle = System.Windows.Markup.XamlReader.Load((e.Result as System.Xml.Linq.XElement).ToString()) as Style;

                    if (dynamicstyle != null)
                    {
                         foreach (UIElement objUielement in this.maingrid.Children.Where(u => u.GetType().ToString() == "JakayaConvo.barcontrol"))
                        {
                            barcontrol objBarControl = null;
                            try
                            {
                                objBarControl = objUielement as barcontrol;
                               objBarControl.btnall.Style = dynamicstyle;
                            }
                            catch (Exception)
                            { }
                            finally
                            {
                                objBarControl = null;
                            }
                        }
                        

                    }
                }
            }
            catch (Exception ex) { }

            finally
            {
                
            }
        }

 
So tell me where I am wrong And how to do this. Plzzzzzzzzz Its really urgent
"1.0" encoding="utf-8" ?>-->
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Key="stylebtnallclick" TargetType="Button"> "FontSize" Value="10"/> "Background" Value="#FF1F3B53"/>--> "Foreground" Value="Red"/> "Padding" Value="3"/> "Content" Value="Hello"/> "ContentTemplate" Value="Hello"/> "BorderThickness" Value="1"/> "BorderBrush"> "0.5,1" StartPoint="0.5,0"> "#FFA3AEB9" Offset="0"/> "#FF8399A9" Offset="0.375"/> "#FF718597" Offset="0.375"/> "#FF617584" Offset="1"/> "Template"> "Button"> "CommonStates"> "Normal"/> "MouseOver"> "BackgroundAnimation" Storyboard.TargetProperty="Opacity"> "0" Value="1"/> "BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)"> "0" Value="#7FFFFFFF"/> --> "Pressed"> "BackgroundAnimation" Storyboard.TargetProperty="Opacity"> "0" Value="1"/> "BackgroundGradient" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Color)"> "0" Value="#D8FFFFFF"/> "BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)"> "0" Value="#3FFFFFFF"/> "Disabled"> "DisabledVisualElement" Storyboard.TargetProperty="Opacity"> "0" Value=".55"/> --> "FocusStates"> "Focused"> "FocusVisualElement" Storyboard.TargetProperty="Opacity"> "0" Value="1"/> --> "Unfocused"/> "Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> "1" Background="{TemplateBinding Background}" Opacity="0.25"> "BackgroundAnimation" Background="#FF62E4FF"/> "BackgroundGradient" Fill="#FF62E4FF"> "contentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="0,0,0,1"/> "DisabledVisualElement" Fill="#FFFFFFFF" RadiusX="0" RadiusY="0" IsHitTestVisible="false" Opacity="0"/> "FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="0" RadiusX="0" RadiusY="0" Margin="1" IsHitTestVisible="false" Opacity="0"/>

Thanks And Regards

salonVB
salonVB

Member

Member

4 points

6 Posts

Re: Changing a button's style in runtime ?

Don't make things too complicated.

Do one thing, when u apply first time write this:

 bt.Style = (Style)this.Resources["activated"];

And when u want to reapply the style, u can search for the key in Resources and if exists then remove the key and readd the new style. Like following :

if (this.Resources.Contains("activated")) this.Resources.Remove("activated");

this.Resources.Add("activated", (XamlReader.Load("ActivatedStyleString")));

where "ActivatedStyleString" is the new style tag string.

This is Silverlight's feature, that u can't apply style twice to a control, u need to remove the style key and reapply the style.

Hergerger
Hergerger

Member

Member

2 points

1 Posts

Re: Changing a button's style in runtime ?

@salonVB Hi salonVB. I had the same id as you, but the button will not change its appearence. Is there anything else to do (e.g. invalidate, update layout, etc.) or should it be enough? Thankx in advance Hergerger

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities