简体   繁体   English

创建按钮并将其放置在某些xaml窗口中,而无需使用xaml代码

[英]Creating button and placing it on certain xaml window without using xaml code

I made a button, set up his margins, height, width in my Window.xaml.cs file: 我做了一个按钮,在我的Window.xaml.cs文件中设置了其边距,高度,宽度:

Button b = new Button();
b.Margin = new Thickness(10, 10, 10, 10);
b.Content= "Button";
b.Height = 50;
b.Width = 50;

I want it to show up on my Window.xaml window when i start the program. 启动程序时,我希望它显示在Window.xaml窗口中。 Using only these few properties is not showing it. 仅使用这几个属性不会显示它。

I could go in Window.xaml file and type in grid or wherever: 我可以进入Window.xaml文件并在网格中或任何地方键入:

<Button Margin="10,10,10,10" Content="Button" Height="50" Width="50"></Button>

And it would show this button in the widnow, but using only these properites (in .cs code), is not enough 它将在widnow中显示此按钮,但是仅使用这些属性(在.cs代码中)是不够的

I assume you only instantiated the button. 我假设您仅实例化了按钮。 The button doesn't know where it should be on the screen. 该按钮不知道它应该在屏幕上的什么位置。 It must be assigned to a named parent control like a grid or stackpanel. 必须将其分配给已命名的父控件,例如网格或堆栈面板。

XAML: XAML:

<Window>
<Grid x:Name="RootGrid">
</Grid>
</Window>

Code behind: 后面的代码:

RootGrid.Children.Add(b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM