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?
The styles can be set only once (sealed after compiling), you can't change it with code
so the solutions are
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
change the property directly
btnCancel.FontSize=30.0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With