开发者

how to add a xaml button in c#

开发者 https://www.devze.com 2023-03-19 14:06 出处:网络
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 expr开发者_如何学Cession blend, but I cant figure out how

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 expr开发者_如何学Cession 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!


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);


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消