Toadums
Toadums

Reputation: 2812

how to add a xaml button in c#

So I created a button in xaml (made a rectangle > right click > create control > button)

I can add it when I am in the xaml designer part of expression blend, but I cant figure out how to create them programmatically in c#.

supposed I named the new button btn_openRecent, then I want to do something like this:

btn_openRecent newBtn = new btn_openRecent();

Can I do this? I have saved it as an application resource, if that makes any difference.

Thanks!

Upvotes: 0

Views: 8161

Answers (2)

Rachel
Rachel

Reputation: 132548

Your CustomButton is either a UserControl or a regular Button with a customized Template

If it's a UserControl, you can use

MyCustomButton newBtn = new MyCustomButton();

If it's a template (more likely scenario) you would create a regular button and apply a style or a template

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

Upvotes: 1

Vlad
Vlad

Reputation: 35584

In XAML, you declare instances of class Button, and assign values to some properties. So, the object created in XAML as

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

can be created in C# as

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

If you have put something into the application's resources, you can get it by using

Button b = (Button)Application.Current.Resources["key"];

But I wouldn't recommend such a technique, since the button cannot be reused more than once.

Note that usually XAML serves one more purpose: putting the control into some another control. So the code like

<Grid>
    <Button>Test</Button>
</Grid>

is expressed in C# as

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

Upvotes: 2

Related Questions