Open棟梁Project - マイクロソフト系技術情報 Wiki
XAMLは、XMLをベースとしており、XAMLの各要素からCLRオブジェクトをインスタンス化し、「要素ツリー」を構築できる。
ここでは、WPFのXAMLの書き方を通して、
を説明する。
XAMLにおける各種の名前空間の宣言は、xmlns属性を使用したXML名前空間にて行う。
ここでは、以下の既定の名前空間の宣言を例にとって説明する。
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
2行目のXML名前空間の宣言(xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation")では、
WPFフレームワーク(PresentationFramework?.dll)のアセンブリ内に同梱されるURIにマップされた
CLR名前空間(System.Windows.Controls、System.Windows.Dataなど)を、既定のXML名前空間(プレフィックスなし)として割り当てている。
そのため、既定でXAMLからWPFフレームワークのCLRオブジェクトを利用できる。
3行目のXML名前空間の宣言(xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml")では、
URIにマップされた共通的なXAMLの言語機能がXML名前空間(x)として割り当てられている。
これにより、「x:」というプレフィックスを使用することで、「言語機能」で説明する、XAMLの言語機能を使用できるようになる。
CLR名前空間について以下を例にとって説明する。
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:igDP="http://infragistics.com/DataPresenter" <--- 名前空間の宣言(追加 Title="Window1" Height="300" Width="300"> <Grid> <igDP:XamDataGrid Name="xamDataGrid1"/> <--- 名前空間の使用例 </Grid> </Window>
Infragistics社製のNetAdvantage?など、XmlnsDefinition?アセンブリ属性でURIとCLR名前空間のマップが指定されたサードパーティ製のUIコンポーネントをD&DでVSデザイナから追加した場合、上記の例のように自動的にXML名前空間の宣言が追加される。
なお、XML名前空間には一意の名前を自由に付与でき(上記の例ではigDP)、このプレフィックスを使用することで、XAMLからUIコンポーネントのCLRオブジェクトを利用できる。
この他に、URIとしてCLR名前空間とアセンブリを直接指定する方法もある。
xmlns:sys="clr-namespace:(CLR名前空間);assembly=(アセンブリ名)"
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:igDP="clr-namespace:Infragistics.Windows.DataPresenter;assembly=Infragistics3・・・" <--- 名前空間の宣言 Title="Window1" Height="300" Width="300"> <Grid> <igDP:XamDataGrid Name="xamDataGrid1"/> <--- 名前空間の使用例
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" <--- 名前空間の宣言 Title="Window1" Height="300" Width="300"> <Window.Resources> <x:Array x:Key="List" Type="{x:Type sys:String}"> <--- 名前空間の使用例
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:uc="clr-namespace:WpfApplication1" <--- 名前空間の宣言 Title="Window1" Height="300" Width="300"> <StackPanel Orientation="Vertical"> <uc:UserControl1 x:Name="userControl1"/> <--- 名前空間の使用例
XAMLの言語機能である
について説明する。
XAMLの言語機能が提供する各種ディレクティブについて説明する。
項番 | ディレクティブ | 説明 |
例 | ||
1 | x:Class | XAML上から分離クラス(コードビハインド)のクラス名を定義する。 |
<Window x:Class="WpfApplication1.Window1" | ||
2 | x:Subclass | パーシャル クラスをサポートしない言語で使用する。通常は利用しない。 |
- | ||
3 | x: ClassModifier? | クラスのアクセスレベルを変更する。通常は利用しない。 |
- | ||
4 | x:Code | XAML上にインラインコードを実装する場合に使用する。通常は利用しない。 |
<Grid> <x:Code> <![CDATA[ void button1_Click(object sender, RoutedEventArgs? e) { button1.Content = "Hello World"; } ]]> </x:Code> <Button Name="button1" Click="button1_Click">Button</Button> </Grid> | ||
5 | x:FieldModifier? | プロパティのアクセスレベルを変更する。通常は利用しない。 |
- | ||
6 | x:Key | XAMLで定義された各種「リソース」を識別する。下記は、x:Keyを使用して「スタイル」の「リソース」をボタンに「データ バインディング」する例。 |
<Window.Resources> <Style x:Key="buttonStyle" TargetType?="{x:Type Button}"> <Setter Property="Background" Value="LightYellow?" /> </Style> </Window.Resources> <Grid> <Button Style="{StaticResource? buttonStyle}">Hello Style</Button> </Grid> | ||
7 | x:Name | XAMLで生成したCLRオブジェクトに名前を付与する。Name属性と差異は無い。 |
<Button x:Name="button1"> Click Here </Button> | ||
8 | x:Shared | 静的なリソースを、取得の度に生成する場合に使用する。通常は利用しない。 ※ true : 静的(全てのインスタンスは同じ) false : 動的(取得の度に生成する) 既定値 : true |
- | ||
9 | x:TypeArguments? | ジェネリックの型引数をコンストラクタに渡す。 (.NET Framework 4.0のXAML 2009からのサポート) |
<!-- XAML 2009 --> <ObservableCollection? x:TypeArguments?="Employee"> <l:Employee FirstName?="John" Name="Doe" /> <l:Employee FirstName?="Tim" Name="Smith" /> </ObservableCollection?> | ||
10 | x:Uid | ローカライゼーションのプロセスとツールによって使用される一意識別子を指定する 。 |
- | ||
11 | xml:lang | カルチャ情報を宣言する。 |
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xml:lang="ja-JP" |
XAMLの言語機能が提供する各種「マークアップ拡張」について説明する。
通常、「マークアップ拡張」は、「{」と「}」の2つの中括弧を使用することでXAMLパーサに対し、拡張されたプロパティ指定方法を指示する。
以下、XAMLの機能である「XAMLで定義されたマークアップ拡張」を一覧する。
これらの種類は、中括弧+「x:」プレフィックスの直後の文字列トークンによって識別される。
項番 | 文字列トークン | 説明 |
例 | ||
1 | x:Static | 静的プロパティ(定数、静的プロパティ、フィールド、列挙値)を参照する。 構文:<object property="{x:Static Member=prefix:typeName.staticMemberName?}" .../> |
<Button Foreground="{x:Static Member=SystemColors?.InfoTextBrush?}" Background="{x:Static Member=SystemColors?.InfoBrush?}"> Click Here </Button> | ||
2 | x:Null | CLRオブジェクトのプロパティにnull値を設定する(既定値をnullクリアする場合など)。 |
<Button x:Name="button1" Background="{x:Null}" Click="button1_Click"> Click Here </Button> | ||
3 | x:Type | CLRクラスの型情報を指定する。 |
詳しくは、下記、項番4の例を参照のこと。 | ||
4 | x:Array | IEnumerableを持つArrayオブジェクト(配列)を生成する。 |
<Window.Resources> <x:Array x:Key="List" Type="{x:Type sys:String}"> <sys:String>A</sys:String> <sys:String>B</sys:String> <sys:String>C</sys:String> </x:Array> </Window.Resources> <StackPanel?> <ListBox? ItemsSource?="{Binding Source={StaticResource? List}}"/> </StackPanel?> ※ 先頭で、.NET FrameworkのSystem名前空間のインポートが必要 xmlns:sys="clr-namespace:System;assembly=mscorlib" ※ StaticResource?については次項で説明する。 |
※ x:Arrayは、例外的に中括弧と共に使用しない。
以下、WPF の機能である「WPF固有のマークアップ拡張」を一覧する。
こちらは、プロパティ値に「データ バインディング」や、「リソース」への参照を指定できる。
項番 | 文字列トークン | 説明 |
構文 ※ 「プロパティ属性構文」と「プロパティ要素構文」については、後述する。 | ||
1 | {Binding ・・・ | Bindingオブジェクトに「バインディング ターゲット」のプロパティを設定することで、「データ バインディング」を実装する。 MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能 > バインディングのマークアップ拡張機能 http://msdn.microsoft.com/ja-jp/library/ms750413.aspx |
具体例は、「データ バインディングの基礎」を参照のこと。 | ||
2 | {StaticResource? ・・・ | 既に定義されたリソースに対する参照を検索し、任意のXAMLプロパティ属性の値を設定する。 |
具体例は、「リソースとのデータ バインディング」を参照のこと。 プロパティ属性構文: <object property="{StaticResource? key}" .../> なお、「データ バインディング」で使用する場合は、次のようになる。 <object property="{Binding Source={StaticResource? key} ...}" .../> プロパティ要素構文: <object> <object.property> <StaticResource? ResourceKey?="key" .../> </object.property> </object> | ||
3 | {DynamicResource? ・・・ | リソースが変化したときに、任意のXAMLプロパティ属性の値を設定する。 keyには、x:Key属性によって指定された既存の「リソース」に対応するキーを指定する。 |
具体例は、「リソースとのデータ バインディング」を参照のこと。 プロパティ属性構文: <object property="{DynamicResource? key}" .../> なお、「データ バインディング」で使用する場合は、次のようになる。 <object property="{Binding Source={DynamicResource? key} ...} " .../> プロパティ要素構文: <object> <object.property> <DynamicResource? ResourceKey?="key" .../> </object.property> </object> | ||
4 | {RelativeSource? ・・・ | Binding.RelativeSource?を指定する。詳しくは、下記のURLを参照のこと。 また、次ページで例を挙げて説明する。 MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能 > RelativeSource?のマークアップ拡張機能 http://msdn.microsoft.com/ja-jp/library/ms743599.aspx |
具体例は、次ページを参照のこと。 プロパティ属性構文: <Binding RelativeSource?="{RelativeSource? modeEnumValue?}" .../> なお、「データ バインディング」で使用する場合は、次のようになる。 <object property="{Binding RelativeSource?={RelativeSource? modeEnumValue?} ...}" .../> プロパティ要素構文: <Binding> <Binding.RelativeSource?> <RelativeSource? Mode="modeEnumValue?"/> </Binding.RelativeSource?> </Binding> OR <Binding> <Binding.RelativeSource?> <Relative Mode="FindAncestor?" AncestorType?="{x:Type typeName}" AncestorLevel?="intLevel"/> </Binding.RelativeSource?> </Binding> | ||
5 | {TemplateBinding? ・・・ | 親コントロールに適用したプロパティ値を「テンプレート」に反映させる。 MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能 > TemplateBinding?のマークアップ拡張機能 http://msdn.microsoft.com/ja-jp/library/ms742882.aspx |
具体例は、「テンプレート」を参照のこと。 プロパティ属性構文: <object property="{TemplateBinding? TargetProperty? }" .../> | ||
6 | {ThemeDictionary? ・・・ | カスタム コントロールの作成者やサードパーティ製のUIコンポーネントの、 コントロールの「スタイル」をアプリケーションの「リソース」から読み込む。 MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能 > ThemeDictionary?のマークアップ拡張機能 http://msdn.microsoft.com/ja-jp/library/ms752067.aspx |
- |
※ keyには、x:Keyディレクティブによって指定された既存のリソースに対応するキーを指定する。
以下、RelativeSource?の「マークアップ拡張」について、XAMLサンプルを用いて説明する。
なお、Button.Template以下の要素(→ 「テンプレート」)については、「テンプレート」を参照のこと。
<StackPanel> <TextBlock Text="{Binding RelativeSource ={RelativeSource Self}, Path=FontFamily}" />・・・(1) <Border Background="Black" Height="5"/> <TextBlock Text="{Binding RelativeSource ={RelativeSource AncestorType={x:Type StackPanel}},Path=Orientation}" />・・・(2) <Border Background="Black" Height="5"/> <Button Content="Hello world"> <Button.Template> <ControlTemplate TargetType="{x:Type Button}"> <ContentPresenter Content="{Binding RelativeSource ={RelativeSource TemplatedParent}, Path=Content}" />・・・(3) </ControlTemplate> </Button.Template> </Button> </StackPanel>
#ref(): File not found: "RenderingResult.png" at page "XAMLの書き方"
プロパティの設定方法として、
の2つの構文について説明する。
以下、TextBox?要素に対して、同等の属性を設定する
「プロパティ属性構文」と「プロパティ要素構文」の例を示す。
要素の属性にテキストを使用してプロパティを設定する方法
<TextBox Width = "100" FontSize = "30" Text = "text1" Background = "White" Foreground = "Blue" />
要素のinnerText・innerXMLを使用してプロパティを設定する方法
<TextBox> <TextBox.Width>100</TextBox.Width> <TextBox.FontSize>30</TextBox.FontSize> <TextBox.Background> <SolidColorBrush Color="White"/> </TextBox.Background> <TextBox.Foreground> <SolidColorBrush Color="Blue"/> </TextBox.Foreground> <TextBox.Text>text1</TextBox.Text> </TextBox>
なお、子要素のコレクションを設定する「プロパティ要素構文」である
などは、暗黙的に使用されるため明記が不要のものもある。
XAMLパーサは、XAMLの「プロパティ属性構文」として指定された各属性テキストを、
プリミティブ型に変換できるリテラル文字列として解釈するか、「型コンバータ」を使用してオブジェクトに変換する。
なお、「型コンバータ」(と、そのベース クラスであるTypeConverter?クラス)は、
.NETのコンポーネントとコントロールのデザイン時・実行時の動作を実装する一般的なクラスであり、WPF独自のクラスではない。
しかし、XAMLの「プロパティ属性構文」からのCLRプロパティ設定を多用するWPF / Silverlight開発では、その存在を認識しておいたほうが良い。
XAMLパーサは通常、プロパティの型(CLRクラス)にTypeConverterAttribute?属性 が付与されているかを調べる。
付与されている場合は、この属性値に基づいた「型コンバータ」を使って、TypeConverter?.ConvertFrom?メソッド により文字列をプロパティ値に変換する。
以下は、ユーザ コントロールに、MyPoint?というカスタムの型を取るCLRプロパティを実装しXAMLに公開、
XAMLの「プロパティ属性構文」として指定された各属性テキストを、カスタムの型に変換する「型コンバータ」を実装した例である。
MyPoint?というカスタム型(型コンバータを実装)
/// <summary> /// カスタム型(型コンバータを実装) /// </summary> [TypeConverter(typeof(MyPointConverter))] public class MyPoint { public MyPoint(int x, int y) { this._x = x; this._y = y; } private int _x; public int X { set { this._x =value; } get { return this._x; } } private int _y; public int Y { set { this._y = value; } get { return this._y; } } }
/// <summary>カスタム型の型コンバータ</summary> public class MyPointConverter : TypeConverter { /// <summary>CanConvertFrom(変換可能かチェックする)</summary> public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <summary>指定された文字列をカスタム型(MyPoint)に変換する</summary> public override object ConvertFrom( ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string[] v = ((string)value).Split(new char[] { ',' }); return new MyPoint(int.Parse(v[0]), int.Parse(v[1])); } return base.ConvertFrom(context, culture, value); } /// <summary>指定されたカスタム型(MyPoint)を文字列に変換する</summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { return ((MyPoint)value).X + "," + ((MyPoint)value).Y; } return base.ConvertTo(context, culture, value, destinationType); } }
MyPoint?というカスタム型のCLRプロパティを実装
/// <summary> /// UserControl1.xaml の相互作用ロジック /// </summary> public partial class UserControl1 : UserControl { // CLRプロパティの定義(XAML属性に公開可能) private MyPoint _myLocation; public MyPoint MyLocation { set { this._myLocation = value; } get { return this._myLocation; } } ・・・
上記のユーザ コントロールのカスタムの型を取るCLRプロパティを、以下のようにXAMLの「プロパティ属性構文」として指定された各属性テキストから初期化できる。
<uc:UserControl1 x:Name="userControl1" MyLocation="10,20"/>
ただし、(当然ながら、)文字列からの変換をサポートしているだけで、すべてのプロパティ値をサポートすることはできない。
文字列で表現できないプロパティ値は、「プロパティ属性構文」ではなく「プロパティ要素構文」として記述する方法を取る。
「コンテンツ構文」とは、Contentプロパティ(またはItemsコレクション プロパティ)に要素を設定する構文である。
ContentPropertyAttribute?を付けることで、通常、属性に指定されるContentプロパティを、要素のinnerText・innerXMLとして記述できるようになる。
<Button Content="Click Here" />
<Button>Click Here</Button>
なお、WindowsフォームやWebフォーム(HTML)などで、
UIコントロールの表示のカスタマイズをするには、
UIコントロールの「スタイル」属性の指定による方法のみサポートされていた。
これに対し、WPFのUIコントロールは「スタイル」属性の指定による方法だけでなく、
Contentプロパティ(またはItemsコレクション プロパティ)に任意の型の子要素を設定することができるため、
コントロールの「外観」を自由に変更でき、柔軟性が非常に高くなっている。
WPFのContentControl?は、Contentプロパティに任意の型の子要素を設定することができるため、コントロールの「外観」を自由に変更できる。
#ref(): File not found: "ContentString.png" at page "XAMLの書き方"
ContentControl?のButtonコントロールを例にしてContentプロパティへ要素を設定する例を示す。
<Button Width="200" Height="200" Content="ボタン"/>
<Button Width="200" Height="200">ボタン</Button>
#ref(): File not found: "ContentImage.png" at page "XAMLの書き方"
Contentプロパティには、Imageオブジェクトなどの任意の型の要素も設定できる。
<Button Width="200" Height="200"> <Button.Content> <Image Source=".\Blue hills.jpg"/> </Button.Content> </Button>
#ref(): File not found: "ContentStringAndImage.png" at page "XAMLの書き方"
<Button Width="200" Height="200"> <Button.Content> <StackPanel Orientation="Vertical"> <Image Source=".\Blue hills.jpg" Margin="5" /> <TextBlock Text="ボタン" HorizontalAlignment="Center" Margin="5"/> </StackPanel> </Button.Content> </Button>
<Button Width="200" Height="200"> <StackPanel Orientation="Vertical"> <Image Source=".\Blue hills.jpg" Margin="5" /> <TextBlock Text="ボタン" HorizontalAlignment="Center" Margin="5"/> </StackPanel> </Button>
WPFのItemsControl?は、Itemsコレクション プロパティに任意の型の子要素を設定することができるため、コントロールの「外観」を自由に変更できる。
ItemsControl?のItemsコレクション プロパティへは、複数のコンテンツを追加できる。
以下、ListBox?コントロールを例にしてItemsコレクション プロパティへ子要素の設定する例を示す。
#ref(): File not found: "ItemsControl.png" at page "XAMLの書き方"
<Grid> <ListBox> <Border BorderBrush ="Black" BorderThickness ="1" Margin="5"> <StackPanel Orientation="Horizontal" Height="120" Width="250" Margin="5"> <Image Source=".\Blue hills.jpg" Height="100"/> <TextBlock Text="Blue hills" VerticalAlignment="Center"/> </StackPanel> </Border> <Border BorderBrush ="Black" BorderThickness ="1" Margin="5"> <StackPanel Orientation="Horizontal" Height="120" Width="250" Margin="5"> <Image Source=".\Sunset.jpg" Height="100"/> <TextBlock Text="Sunset" VerticalAlignment="Center"/> </StackPanel> </Border> <Border BorderBrush ="Black" BorderThickness ="1" Margin="5"> <StackPanel Orientation="Horizontal" Height="120" Width="250" Margin="5"> <Image Source=".\Water lilies.jpg" Height="100"/> <TextBlock Text="Water lilies" VerticalAlignment="Center"/> </StackPanel> </Border> <Border BorderBrush ="Black" BorderThickness ="1" Margin="5"> <StackPanel Orientation="Horizontal" Height="120" Width="250" Margin="5"> <Image Source=".\Winter.jpg" Height="100"/> <TextBlock Text="Winter" VerticalAlignment="Center"/> </StackPanel> </Border> </ListBox> </Grid>