【问题标题】:WPF. Use button style which is in xaml in code behindWPF。在后面的代码中使用 xaml 中的按钮样式
【发布时间】:2015-10-19 08:05:50
【问题描述】:

我在代码后面创建按钮,现在必须使用 xaml 中的样式,如何在 c# 中为我的按钮调用该样式?

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 x:Key="ButtonStyle" TargetType="{x:Type Button}">

【问题讨论】:

    标签: c# wpf xaml styles code-behind


    【解决方案1】:

    只需设置它:

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

    请注意,来自Resources 字典的项目必须转换为它们的实际类型。

    话虽如此,您不应该在代码隐藏中创建控件。在 99.99% 的情况下,您应该在 XAML 中执行此操作并在那里分配样式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 2010-12-30
      • 2015-02-04
      • 2016-04-06
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多