System.InvalidOperationException: 'After a 'SetterBaseCollection' is in use (sealed), it cannot be modified.' occurs when adding additional property for a Style in code behind RRS feed

  • Question

  • Hi Team,

    I have defined a style for Button in App.Xaml as given below. 

         <Style TargetType="Button" x:Key="buttonStyle"> 
               <Setter Property="Background" Value="Orange"/>  

    I need to set this style for a button when the button is clicked. But I need to add some more properties for this style in code behind before assigning this to the button. I have used the following code for this. 


    private void Button_Click(object sender, RoutedEventArgs e)
        Style buttonStyle = App.Current.Resources["buttonStyle"] as Style;
        buttonStyle.Setters.Add(new Setter(Button.FontSizeProperty, (double)16));
        this.button.Style = buttonStyle;

    But this causes the application to crash with the below given exception. 

    Is there any other way to add additional property to the style in code behind which is already defined in App.Xaml?

    Please suggest me on this. Thanks in advance. 


    Mohanram A.

    • Edited by Mohanram A Thursday, December 10, 2020 1:43 PM
    Thursday, December 10, 2020 1:42 PM

All replies

  • Try a different approach:

    this.button.Style = (Style)App.Current.Resources["buttonStyle2"];

    where buttonStyle2 is the second style:


        <Style TargetType="Button" x:Key="buttonStyle">

            <Setter Property="Background" Value="Orange"/>


        <Style TargetType="Button" x:Key="buttonStyle2"

               BasedOn="{StaticResource buttonStyle}">

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



    Thursday, December 10, 2020 5:21 PM