XAML 与 C# 代码
您可以使用 XAML 创建、初始化和设置对象的属性。也可以使用编程代码执行相同的活动。
XAML 只是设计 UI 元素的另一种简单易行的方法。使用 XAML,您可以决定是否要在 XAML 中声明对象或使用代码声明它们。
让我们举一个简单的例子来演示如何用 XAML 编写 −
<Window x:Class = "XAMLVsCode.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "525">
<StackPanel>
<TextBlock Text = "Welcome to XAML Tutorial" Height = "20" Width = "200" Margin = "5"/>
<Button Content = "Ok" Height = "20" Width = "60" Margin = "5"/>
</StackPanel>
</Window>
在此示例中,我们创建了一个带有按钮和文本块的堆栈面板,并定义了按钮和文本块的一些属性,例如高度、宽度和边距。编译并执行上述代码时,将产生以下输出 −
现在查看用 C# 编写的相同代码。
using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace XAMLVsCode {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
// Create the StackPanel
StackPanel stackPanel = new StackPanel();
this.Content = stackPanel;
// Create the TextBlock
TextBlock textBlock = new TextBlock();
textBlock.Text = "Welcome to XAML Tutorial";
textBlock.Height = 20;
textBlock.Width = 200;
textBlock.Margin = new Thickness(5);
stackPanel.Children.Add(textBlock);
// Create the Button
Button button = new Button();
button.Content = "OK";
button.Height = 20;
button.Width = 50;
button.Margin = new Thickness(20);
stackPanel.Children.Add(button);
}
}
}
当上述代码被编译并执行时,它将产生以下输出。注意,它与XAML代码的输出完全相同。
现在您可以看到使用和理解XAML是多么简单。

