Change the setter value in style

I am programming in WPF (C #). I am trying to change a value in a style installer.

my style:

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

and I use it with the 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 I'm trying to do this:

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

after setting the font size to 30Am I getting this error?

After the "SetterCollectionBase" is used (sealed), it cannot be changed

How can I solve this problem?

+4
source share
3 answers

Since you are doing a clean user interface and behind the code, some answers recommend that you use MVVM, which will really make things a lot easier.

? , FontSize? , Click , .

,

 private void btnCancel_Click_1(object sender, RoutedEventArgs e)
    {
        var button = sender as Button;
        if (button != null) button.FontSize = 30;
    }
+1

( ),

  •     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));
    

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

  • btnCancel.FontSize=30.0;
    
+8

, - ( MVVM Lite ViewModelBase, -, ):

public class MyViewModel : ViewModelBase
{
    private double _FontSize = 0.0;
    public double FontSize
    {
        get { return this._FontSize; }
        set { this._FontSize = value; RaisePropertyChanged(() => this.FontSize); }
    }
}

:

public partial class Window1 : Window
{
    public MyViewModel MyViewModel {get; set;}
    public Window1()
    {
        InitializeComponent();
        this.MyViewModel = new MyViewModel { FontSize = 80 };
    }
}

, :

<Window.Resources>
    <Style TargetType="Control" x:Key="st">
        <Setter Property="FontFamily" Value="Tahoma"/>
        <Setter Property="FontSize" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}, Path=MyViewModel.FontSize}"/>
    </Style>
</Window.Resources>
0
source

All Articles