如何在c#中添加一个xaml按钮

本文关键字:一个 xaml 按钮 添加 | 更新日期: 2023-09-27 18:01:48

所以我在xaml中创建了一个按钮(创建了一个矩形)

我可以添加它,当我在表达式混合的xaml设计器部分,但我不知道如何在c#中以编程方式创建它们。

假设我将新按钮命名为btn_openRecent,然后我想做这样的事情:

btn_openRecent newBtn = new btn_openRecent();

我可以这样做吗?我已经将其保存为应用程序资源,如果这有什么不同的话。

谢谢!

如何在c#中添加一个xaml按钮

在XAML中,您声明类Button的实例,并为一些属性赋值。因此,在XAML中创建的对象为

<Button Click="OnClick">Test</Button>

可以在c#中创建为

Button b = new Button();
b.Content = "Test";
b.Click += OnClick;

如果你在应用程序的资源中放了一些东西,你可以使用

来获取它
Button b = (Button)Application.Current.Resources["key"];

但我不推荐这种技术,因为按钮不能重复使用多次。

注意,XAML通常还有一个目的:将控件放入另一个控件中。所以像

这样的代码
<Grid>
    <Button>Test</Button>
</Grid>

在c#中表示为

Grid g = new Grid();
Button b = new Button();
b.Content = "Test";
g.Children.Add(b);

您的CustomButton是一个UserControl或一个常规的按钮与自定义的Template

如果它是UserControl,你可以使用

MyCustomButton newBtn = new MyCustomButton();

如果它是一个模板(更有可能的情况),您将创建一个常规按钮并应用样式或模板

Button newBtn = new Button();
newBtn.Template = (ControlTemplate)FindResource("MyCustomButtonTemplate");
// Or if your Template is defined in a Style
newBtn.Style= (Style)FindResource("MyCustomButtonStyle");