WPF. Use button style which is in xaml in code behind

时间:2015-07-28 16:16:22

标签: c# wpf xaml styles code-behind

I create button behind code and now have to use Style which is in xaml, how can I call that style in c# for my button?

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {

           var button1 = new Button();

            TestPanel.Children.Add(button1);
        }
    }
}

Style is <Style x:Key="ButtonStyle" TargetType="{x:Type Button}">

1 个答案:

答案 0 :(得分:1)

Just set it:

Style myStyle = (Style)Resources["ButtonStyle"];
button1.Style = myStyle;

Note that items coming out of the Resources dictionary must be cast to their actual type.

That being said, you shouldn't be creating controls in code-behind. In 99.99% of cases you should be doing this in XAML and assigning the style there.