Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change setter value in style

Tags:

c#

styles

wpf

xaml

I'm programming in WPF(c#). I'm trying to change value in a setter of style.

my style is:

<Style TargetType="Control" x:Key="st">
    <Setter Property="FontFamily" Value="Tahoma"/>
    <Setter Property="FontSize" Value="14"/>
</Style>

and I use it in a button:

<Button x:Name="btnCancel" Style="{StaticResource st}" Content="انصراف" Canvas.Left="30" Canvas.Top="18" Width="139" Height="53" FontFamily="2  badr" FlowDirection="LeftToRight" Click="btnCancel_Click_1" />

and what I try to do is this code:

Style style = new Style();
style = (Style) Resources["st"];
Setter setter =(Setter) style.Setters[1];
setter.Value = 30;

after setting font size to 30 I get this error?

After a “SetterCollectionBase” is in use (sealed), it cannot be modified

How can I solve this problem?

like image 669
Babak.Abad Avatar asked Dec 26 '22 16:12

Babak.Abad


1 Answers

The styles can be set only once (sealed after compiling), you can't change it with code

so the solutions are

  1. create a style by code

        Style st = new Style(typeof(System.Windows.Controls.Control));
        st.Setters.Add(new Setter(Control.FontFamilyProperty, new FontFamily("Tahoma")));
        st.Setters.Add(new Setter(Control.FontSizeProperty, 14.0));
    

later you can change it

        st.Setters.OfType<Setter>().FirstOrDefault(X => X.Property == Control.FontSizeProperty).Value = 30.0;//safer than Setters[1]

or

  1. change the property directly

    btnCancel.FontSize=30.0;
    
like image 77
seddik Avatar answered Jan 02 '23 00:01

seddik