Xaml-vs-csharp-code

提供:Dev Guides
移動先:案内検索

XAML Vs C#コード

XAMLを使用して、オブジェクトのプロパティを作成、初期化、および設定できます。 プログラミングコードを使用して同じアクティビティを実行することもできます。

XAMLは、UI要素を設計するためのもう1つのシンプルで簡単な方法です。 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#コード

次に、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#コード出力

これで、XAMLの使用と理解がどれほど簡単であるかがわかります。