我在代码后面创建按钮,现在必须使用 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}">
最佳答案
只需设置它:
Style myStyle = (Style)Resources["ButtonStyle"];
button1.Style = myStyle;
请注意,来自 Resources
字典的项目必须转换为它们的实际类型。
也就是说,您不应该在代码隐藏中创建控件。在 99.99% 的情况下,您应该在 XAML 中执行此操作并在其中分配样式。
关于c# - WPF。在后面的代码中使用 xaml 中的按钮样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31681871/