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> 

在此示例中,我們使用一個按鈕和一個文字塊建立了一個堆疊面板,並定義了按鈕和文字塊的一些屬性,如高度、寬度和邊距。當編譯並執行以上程式碼時,程式碼會生成以下輸出 -

XAML C# Code

現在來看使用 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 程式碼的輸出完全相同。

C# Code Output

現在您應該可以看到使用和理解 XAML 有多簡單了吧。

廣告
© . All rights reserved.