[[Open棟梁Project>http://opentouryo.osscons.jp/]] - [[マイクロソフト系技術情報 Wiki>http://techinfoofmicrosofttech.osscons.jp/]]

-[[戻る>XAML]]

* 目次 [#i1942657]
#contents

*概要 [#u34be5f5]
XAMLは、XMLをベースとしており、XAMLの各要素からCLRオブジェクトをインスタンス化し、「要素ツリー」を構築できる。

ここでは、WPFのXAMLの書き方を通して、
-XAMLの基礎
-XAMLによるUI設計方法
-XAMLによるUI開発方法

を説明する。

*名前空間 [#t16cd178]
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"

-XML名前空間の簡単な説明~
http://www.kanzaki.com/docs/sw/names.html

**WPF名前空間 [#hda52e9d]
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オブジェクトを利用できる。

**XAML名前空間 [#s157df62]
3行目のXML名前空間の宣言(xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml")では、~
URIにマップされた共通的なXAMLの言語機能がXML名前空間(x)として割り当てられている。~
これにより、「x:」というプレフィックスを使用することで、「[[言語機能>#n6cf5f58]]」で説明する、XAMLの言語機能を使用できるようになる。

**CLR名前空間 [#g26a2ab6]
CLR名前空間について以下を例にとって説明する。

***(1) [#ne84959f]

-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名前空間の宣言が追加される。

-MSDN > .NET Frameworkクラス ライブラリ > System.Windows.Markup.XmlAttributeProperties.XmlnsDefinitionプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.markup.xmlattributeproperties.xmlnsdefinition.aspx

なお、XML名前空間には一意の名前を自由に付与でき(上記の例ではigDP)、このプレフィックスを使用することで、XAMLからUIコンポーネントのCLRオブジェクトを利用できる。

***(2) [#z789b34c]
この他に、URIとしてCLR名前空間とアセンブリを直接指定する方法もある。

-CLR名前空間の宣言
 xmlns:sys="clr-namespace:(CLR名前空間);assembly=(アセンブリ名)"
--例1:サードパーティ製品
 <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"/> <--- 名前空間の使用例
--例2:.NET Framework
 <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}"> <--- 名前空間の使用例
--例3:自作の同一プロジェクトのクラス
 <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"/> <--- 名前空間の使用例

-この方法では、「clr-namespace」、「assembly」などの定義済みトークンを使用する。
--当該プロジェクト中のCLR名前空間を指定する場合は、「assembly」トークンは省略できる。
--XML名前空間には一意の名前を自由に付与でき、このプレフィックスを使用することで、XAMLからUIコンポーネントのCLRオブジェクトを利用できる。

-製品並みのカスタムのUIコントロールを開発・使用するなどの目的を除いて、CLRクラスを開発しXAMLから使用する場合、
--一般的には「clr-namespace、assembly」の定義済みトークンを使用する。
--ただし、この方法は、1つのCLR名前空間に対して、1つのXML名前空間しか割り当てられない
--(XmlnsDefinitionアセンブリ属性を使用すると、1つのXML名前空間に複数のCLR名前空間を割り当てられる)。

***参考 [#q56ac959]
-MSDN > WPFの基礎 > WPFのXAML > XAML名前空間およびWPF XAMLの名前空間の割り当て~
http://msdn.microsoft.com/ja-jp/library/ms747086.aspx

*言語機能 [#n6cf5f58]
XAMLの言語機能である
-「[[ディレクティブ>#cd4daa01]]」
-「[[マークアップ拡張>#hc49ac25]]」

について説明する。

-MSDN > .NET Framework XAMLサービスの概念説明のドキュメント > XAML名前空間 (x:) 言語機能~
http://msdn.microsoft.com/ja-jp/library/ms753327.aspx

**ディレクティブ [#cd4daa01]
XAMLの言語機能が提供する各種ディレクティブについて説明する。

|項番|ディレクティブ|説明|h
|~|~|例|h
|1|x:Class|XAML上から分離クラス(コードビハインド)のクラス名を定義する。|
|~|~|<Window x:Class="WpfApplication1.Window1"|
|2|x:Subclass|パーシャル クラスをサポートしない言語で使用する。通常は利用しない。|
|~|~|-|
|3|x: ClassModifier|クラスのアクセスレベルを変更する。通常は利用しない。|
|~|~|-|
|4|x:Code|XAML上にインラインコードを実装する場合に使用する。通常は利用しない。|
|~|~|<Grid>&br;&nbsp;&nbsp;<x:Code>&br;&nbsp;&nbsp;&nbsp;&nbsp;<![CDATA[&br;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;void&nbsp;button1_Click(object&nbsp;sender,&nbsp;RoutedEventArgs&nbsp;e)&nbsp;{&br;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;button1.Content&nbsp;=&nbsp;"Hello&nbsp;World";&br;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&br;&nbsp;&nbsp;&nbsp;&nbsp;]]>&br;&nbsp;&nbsp;</x:Code>&br;&nbsp;&nbsp;<Button&nbsp;Name="button1"&nbsp;Click="button1_Click">Button</Button>&br;</Grid>|
|5|x:FieldModifier|プロパティのアクセスレベルを変更する。通常は利用しない。|
|~|~|-|
|6|x:Key|XAMLで定義された各種「リソース」を識別する。下記は、x:Keyを使用して「スタイル」の「リソース」をボタンに「データ バインディング」する例。|
|~|~|<Window.Resources>&br;&nbsp;&nbsp;<Style&nbsp;x:Key="buttonStyle"&nbsp;TargetType="{x:Type&nbsp;Button}">&br;&nbsp;&nbsp;&nbsp;&nbsp;<Setter&nbsp;Property="Background"&nbsp;Value="LightYellow"&nbsp;/>&br;&nbsp;&nbsp;</Style>&br;</Window.Resources>&br;<Grid>&br;&nbsp;&nbsp;<Button&nbsp;Style="{StaticResource&nbsp;buttonStyle}">Hello&nbsp;Style</Button>&br;</Grid>|
|7|x:Name|XAMLで生成したCLRオブジェクトに名前を付与する。Name属性と差異は無い。|
|~|~|<Button&nbsp;x:Name="button1">&br;&nbsp;&nbsp;&nbsp;Click&nbsp;Here&br;</Button>|
|8|x:Shared|静的なリソースを、取得の度に生成する場合に使用する。通常は利用しない。&br;※&nbsp;true&nbsp;:&nbsp;静的(全てのインスタンスは同じ)&br;&nbsp;&nbsp;&nbsp;false&nbsp;:&nbsp;動的(取得の度に生成する)&br;&nbsp;&nbsp;&nbsp;既定値&nbsp;:&nbsp;true|
|~|~|-|
|9|x:TypeArguments|ジェネリックの型引数をコンストラクタに渡す。&br;(.NET Framework 4.0のXAML 2009からのサポート)|
|~|~|<!--&nbsp;XAML&nbsp;2009&nbsp;-->&br;<ObservableCollection&nbsp;x:TypeArguments="Employee">&br;&nbsp;&nbsp;<l:Employee&nbsp;FirstName="John"&nbsp;Name="Doe"&nbsp;/>&br;&nbsp;&nbsp;<l:Employee&nbsp;FirstName="Tim"&nbsp;Name="Smith"&nbsp;/>&br;</ObservableCollection>|
|10|x:Uid|ローカライゼーションのプロセスとツールによって使用される一意識別子を指定する 。|
|~|~|-|
|11|xml:lang|カルチャ情報を宣言する。|
|~|~|<Window&nbsp;x:Class="WpfApplication1.Window1"&br;&nbsp;&nbsp;xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&br;&nbsp;&nbsp;xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&br;&nbsp;&nbsp;xml:lang="ja-JP"|

-MSDN > Windows Presentation Foundation > グローバライズとローカライズ > WPFのグローバリゼーション~
http://msdn.microsoft.com/ja-jp/library/ms745650.aspx

**マークアップ拡張 [#hc49ac25]
XAMLの言語機能が提供する各種「マークアップ拡張」について説明する。~
通常、「マークアップ拡張」は、「{」と「}」の2つの中括弧を使用することでXAMLパーサに対し、拡張されたプロパティ指定方法を指示する。

-MSDN > WPFの基礎 > WPFのXAML > マークアップ拡張機能とWPF XAML~
http://msdn.microsoft.com/ja-jp/library/ms747254.aspx

***XAMLで定義されたマークアップ拡張 [#x7d4e60c]
以下、XAMLの機能である「XAMLで定義されたマークアップ拡張」を一覧する。~
これらの種類は、中括弧+「x:」プレフィックスの直後の文字列トークンによって識別される。

-XAMLに実装されたマークアップ拡張
|項番|文字列トークン|説明|h
|~|~|例|h
|1|x:Static|静的プロパティ(定数、静的プロパティ、フィールド、列挙値)を参照する。&br;構文:<object property="{x:Static Member=prefix:typeName.staticMemberName}" .../>|
|~|~|<Button&nbsp;&br;&nbsp;&nbsp;&nbsp;&nbsp;Foreground="{x:Static&nbsp;Member=SystemColors.InfoTextBrush}"&br;&nbsp;&nbsp;&nbsp;&nbsp;Background="{x:Static&nbsp;Member=SystemColors.InfoBrush}">&br;&nbsp;&nbsp;Click&nbsp;Here&br;</Button>|
|2|x:Null|CLRオブジェクトのプロパティにnull値を設定する(既定値をnullクリアする場合など)。|
|~|~|<Button&nbsp;x:Name="button1"&nbsp;Background="{x:Null}"&nbsp;Click="button1_Click">&br;&nbsp;&nbsp;Click&nbsp;Here&br;</Button>|
|3|x:Type|CLRクラスの型情報を指定する。|
|~|~|詳しくは、下記、項番4の例を参照のこと。|
|4|x:Array|IEnumerableを持つArrayオブジェクト(配列)を生成する。|
|~|~|<Window.Resources>&br;&nbsp;&nbsp;<x:Array&nbsp;x:Key="List"&br;&nbsp;&nbsp;&nbsp;&nbsp;Type="{x:Type&nbsp;sys:String}">&br;&nbsp;&nbsp;&nbsp;&nbsp;<sys:String>A</sys:String>&br;&nbsp;&nbsp;&nbsp;&nbsp;<sys:String>B</sys:String>&br;&nbsp;&nbsp;&nbsp;&nbsp;<sys:String>C</sys:String>&br;&nbsp;&nbsp;</x:Array>&br;</Window.Resources>&br;<StackPanel>&br;&nbsp;&nbsp;<ListBox&nbsp;ItemsSource="{Binding&nbsp;Source={StaticResource&nbsp;List}}"/>&br;</StackPanel>&br;&br;※&nbsp;先頭で、.NET&nbsp;FrameworkのSystem名前空間のインポートが必要&br;&nbsp;&nbsp;&nbsp;xmlns:sys="clr-namespace:System;assembly=mscorlib"&br;&br;※&nbsp;StaticResourceについては次項で説明する。|

※ x:Arrayは、例外的に中括弧と共に使用しない。

***WPF固有のマークアップ拡張 [#f8bba188]
以下、WPF の機能である「WPF固有のマークアップ拡張」を一覧する。~
こちらは、プロパティ値に「データ バインディング」や、「リソース」への参照を指定できる。

-XAMLに実装されたマークアップ拡張
|項番|文字列トークン|説明|h
|~|~|構文 ※ 「[[プロパティ属性構文>#q550d6b3]]」と「[[プロパティ要素構文>#fa957fd3]]」については、後述する。|h
|1|{Binding&br;・・・|Bindingオブジェクトに「バインディング ターゲット」のプロパティを設定することで、「データ バインディング」を実装する。&br;MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能 > バインディングのマークアップ拡張機能&br;http://msdn.microsoft.com/ja-jp/library/ms750413.aspx|
|~|~|具体例は、「[[データ バインディングの基礎>#bbd76ce0]]」を参照のこと。|
|2|{StaticResource&br;・・・|既に定義されたリソースに対する参照を検索し、任意のXAMLプロパティ属性の値を設定する。|
|~|~|具体例は、「[[リソースとのデータ バインディング>#ac5a7f33]]」を参照のこと。&br;&br;プロパティ属性構文:&br;<object&nbsp;property="{StaticResource&nbsp;key}"&nbsp;.../>&br;&br;なお、「データ&nbsp;バインディング」で使用する場合は、次のようになる。&br;<object&nbsp;property="{Binding&nbsp;Source={StaticResource&nbsp;key}&nbsp;...}"&nbsp;.../>&br;&br;プロパティ要素構文:&br;<object>&br;&nbsp;&nbsp;<object.property>&br;&nbsp;&nbsp;&nbsp;&nbsp;<StaticResource&nbsp;ResourceKey="key"&nbsp;.../>&br;&nbsp;&nbsp;</object.property>&br;</object>|
|3|{DynamicResource&br;・・・|リソースが変化したときに、任意のXAMLプロパティ属性の値を設定する。&br;keyには、x:Key属性によって指定された既存の「リソース」に対応するキーを指定する。|
|~|~|具体例は、「[[リソースとのデータ バインディング>#ac5a7f33]]」を参照のこと。&br;&br;プロパティ属性構文:&br;<object&nbsp;property="{DynamicResource&nbsp;key}"&nbsp;.../>&br;&br;なお、「データ&nbsp;バインディング」で使用する場合は、次のようになる。&br;<object&nbsp;property="{Binding&nbsp;Source={DynamicResource&nbsp;key}&nbsp;...}&nbsp;"&nbsp;.../>&br;&br;プロパティ要素構文:&br;<object>&br;&nbsp;&nbsp;<object.property>&br;&nbsp;&nbsp;&nbsp;&nbsp;<DynamicResource&nbsp;ResourceKey="key"&nbsp;.../>&br;&nbsp;&nbsp;</object.property>&br;</object>|
|4|{RelativeSource&br;・・・|Binding.RelativeSourceを指定する。詳しくは、下記のURLを参照のこと。&br;また、次ページで例を挙げて説明する。&br;&br;MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能 > RelativeSourceのマークアップ拡張機能&br;http://msdn.microsoft.com/ja-jp/library/ms743599.aspx|
|~|~|具体例は、次ページを参照のこと。&br;&br;プロパティ属性構文:&br;<Binding&nbsp;RelativeSource="{RelativeSource&nbsp;modeEnumValue}"&nbsp;.../>&br;&br;なお、「データ&nbsp;バインディング」で使用する場合は、次のようになる。&br;<object&nbsp;property="{Binding&nbsp;RelativeSource={RelativeSource&nbsp;modeEnumValue}&nbsp;...}"&nbsp;.../>&br;&br;プロパティ要素構文:&br;<Binding>&br;&nbsp;&nbsp;<Binding.RelativeSource>&br;&nbsp;&nbsp;&nbsp;&nbsp;<RelativeSource&nbsp;Mode="modeEnumValue"/>&br;&nbsp;&nbsp;</Binding.RelativeSource>&br;</Binding>&br;&nbsp;OR&nbsp;&br;<Binding>&br;&nbsp;&nbsp;<Binding.RelativeSource>&br;&nbsp;&nbsp;&nbsp;&nbsp;<Relative&br;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Mode="FindAncestor"&br;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AncestorType="{x:Type&nbsp;typeName}"&br;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AncestorLevel="intLevel"/>&br;&nbsp;&nbsp;</Binding.RelativeSource>&br;</Binding>|
|5|{TemplateBinding&br;・・・|親コントロールに適用したプロパティ値を「テンプレート」に反映させる。&br;MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能 > TemplateBindingのマークアップ拡張機能&br;http://msdn.microsoft.com/ja-jp/library/ms742882.aspx|
|~|~|具体例は、「[[テンプレート>#bb58b780]]」を参照のこと。&br;&br;プロパティ属性構文:&br;<object property="{TemplateBinding TargetProperty }" .../>|
|6|{ThemeDictionary&br;・・・|カスタム コントロールの作成者やサードパーティ製のUIコンポーネントの、&br;コントロールの「スタイル」をアプリケーションの「リソース」から読み込む。&br;&br;MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能 > ThemeDictionaryのマークアップ拡張機能&br;http://msdn.microsoft.com/ja-jp/library/ms752067.aspx|
|~|~|-|

※ keyには、x:Keyディレクティブによって指定された既存のリソースに対応するキーを指定する。

***RelativeSourceの例 [#z2d77bd5]
以下、RelativeSourceの「マークアップ拡張」について、XAMLサンプルを用いて説明する。~
なお、Button.Template以下の要素(→ 「[[テンプレート>#bb58b780]]」)については、「[[テンプレート>#bb58b780]]」を参照のこと。

-RelativeSourceの例
 <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(RenderingResult.png,left,nowrap,レンダリング結果)

-(1)では、TextBlock要素自身のFontFamilyプロパティを取得して、自身のTextプロパティに設定している。
-(2)では、親要素(AncestorType 属性に指定されているStackPanel型)を検索し、Orientationプロパティを取得して、自身のTextプロパティに設定している。
-(3)では、TemplatedParent 属性により、テンプレートを適用しているControlTemplate(ここでは、ControlTemplateであるButton要素)の~
Contentプロパティを取得し、ContentPresenterクラスのContentプロパティに設定している。

-MSDN > WPFの基礎 > WPFのXAML > WPF XAML拡張機能~
http://msdn.microsoft.com/ja-jp/library/ms747180.aspx

*プロパティの設定方法 [#s1a3f3e9]
プロパティの設定方法として、
-プロパティ属性構文:~
要素の属性にテキストを使用して設定する。
-プロパティ要素構文:~
要素のinnerText・innerXMLを使用してプロパティを設定する。

の2つの構文について説明する。

以下、TextBox要素に対して、同等の属性を設定する~
「[[プロパティ属性構文>#q550d6b3]]」と「[[プロパティ要素構文>#fa957fd3]]」の例を示す。

**プロパティ属性構文 [#q550d6b3]
要素の属性にテキストを使用してプロパティを設定する方法

-プロパティ属性構文の例
 <TextBox 
    Width = "100"
    FontSize = "30"
    Text = "text1"
    Background = "White"
    Foreground = "Blue" />

**プロパティ要素構文 [#fa957fd3]
要素の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>

なお、子要素のコレクションを設定する「[[プロパティ要素構文>#fa957fd3]]」である
-Panel.Childrenプロパティ
-ItemsControl.Itemsプロパティ

などは、暗黙的に使用されるため明記が不要のものもある。

**型コンバータ [#ea68ba77]
XAMLパーサは、XAMLの「[[プロパティ属性構文>#q550d6b3]]」として指定された各属性テキストを、~
プリミティブ型に変換できるリテラル文字列として解釈するか、「型コンバータ」を使用してオブジェクトに変換する。

なお、「型コンバータ」(と、そのベース クラスであるTypeConverterクラス)は、~
.NETのコンポーネントとコントロールのデザイン時・実行時の動作を実装する一般的なクラスであり、WPF独自のクラスではない。~
しかし、XAMLの「[[プロパティ属性構文>#q550d6b3]]」からのCLRプロパティ設定を多用するWPF / Silverlight開発では、その存在を認識しておいたほうが良い。

XAMLパーサは通常、プロパティの型(CLRクラス)にTypeConverterAttribute属性 が付与されているかを調べる。~
付与されている場合は、この属性値に基づいた「型コンバータ」を使って、TypeConverter.ConvertFromメソッド により文字列をプロパティ値に変換する。

以下は、ユーザ コントロールに、MyPointというカスタムの型を取るCLRプロパティを実装しXAMLに公開、~
XAMLの「[[プロパティ属性構文>#q550d6b3]]」として指定された各属性テキストを、カスタムの型に変換する「型コンバータ」を実装した例である。

***カスタム型 [#t4801c54]
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; }
   }
 }

***型コンバータ [#qcb8e5cf]
 /// <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);
   }
 }

***ユーザ コントロール [#mfa54c4b]
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; }
   }
 
 ・・・

***型コンバータの使用例 [#t865d3ca]
上記のユーザ コントロールのカスタムの型を取るCLRプロパティを、以下のようにXAMLの「[[プロパティ属性構文>#q550d6b3]]」として指定された各属性テキストから初期化できる。

 <uc:UserControl1 x:Name="userControl1" MyLocation="10,20"/>

ただし、(当然ながら、)文字列からの変換をサポートしているだけで、すべてのプロパティ値をサポートすることはできない。~
文字列で表現できないプロパティ値は、「[[プロパティ属性構文>#q550d6b3]]」ではなく「[[プロパティ要素構文>#fa957fd3]]」として記述する方法を取る。

-MSDN > WPFの基礎 > WPFのXAML > TypeConverters及びXAML~
http://msdn.microsoft.com/ja-jp/library/aa970913.aspx

*コンテンツ構文 [#v6b58154]
「コンテンツ構文」とは、Contentプロパティ(またはItemsコレクション プロパティ)に要素を設定する構文である。~
ContentPropertyAttributeを付けることで、通常、属性に指定されるContentプロパティを、要素のinnerText・innerXMLとして記述できるようになる。

-MSDN > .NET Frameworkクラス ライブラリ > System.Windows.Markup.ContentPropertyAttributeクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.markup.contentpropertyattribute.aspx
--[ContentPropertyAttribute("Content")]→ Contentプロパティ
--[ContentPropertyAttribute("Items")]→ Itemsコレクション プロパティ

-コンテンツ構文
--プロパティ属性構文
 <Button Content="Click Here" />
--プロパティ要素構文
 <Button>Click Here</Button>

なお、WindowsフォームやWebフォーム(HTML)などで、~
UIコントロールの表示のカスタマイズをするには、~
UIコントロールの「スタイル」属性の指定による方法のみサポートされていた。

これに対し、WPFのUIコントロールは「スタイル」属性の指定による方法だけでなく、~
Contentプロパティ(またはItemsコレクション プロパティ)に任意の型の子要素を設定することができるため、~
コントロールの「外観」を自由に変更でき、柔軟性が非常に高くなっている。

-補足:Windowsフォームの外観の変更
--Windowsフォームの「外観」を変更するには、コントロールを自前で描画する「オーナー描画」と呼ばれる方法が用意されていた。~
しかしながら、「オーナー描画」はグラフィックス メソッドなどを使用して、すべての描画を独自に行わなければならないため、コントロールに対する深い知識と多量のコードが必要であった。

--関連資料
---[[.NETコントロールのカスタマイズ方法]]

**Contentプロパティ [#p8c8ba55]
WPFのContentControlは、Contentプロパティに任意の型の子要素を設定することができるため、コントロールの「外観」を自由に変更できる。

***文字列のコンテンツ要素を格納 [#c30d2d82]
#ref(ContentString.png,left,nowrap,レンダリング結果)

ContentControlのButtonコントロールを例にしてContentプロパティへ要素を設定する例を示す。

-プロパティ属性構文:
 <Button Width="200" Height="200" Content="ボタン"/>
-プロパティ要素構文:
 <Button Width="200" Height="200">ボタン</Button>

***イメージのコンテンツ要素を格納 [#s73b20d0]
#ref(ContentImage.png,left,nowrap,レンダリング結果)

Contentプロパティには、Imageオブジェクトなどの任意の型の要素も設定できる。

 <Button Width="200" Height="200">
   <Button.Content>
     <Image Source=".\Blue hills.jpg"/>
   </Button.Content>
 </Button>

***パネルに纏めた複数のコンテンツ要素を格納 [#a31e6bf2]
#ref(ContentStringAndImage.png,left,nowrap,レンダリング結果)

-2つ以上の要素を設定したい場合は、パネル要素を使用する。
 <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>

-なお、<Object.Content>タグは省略することもできる。
 <Button Width="200" Height="200">
   <StackPanel Orientation="Vertical">
     <Image Source=".\Blue hills.jpg" Margin="5" />
     <TextBlock Text="ボタン" HorizontalAlignment="Center" Margin="5"/>
   </StackPanel>
 </Button>

**Itemsプロパティ [#gb58344b]
WPFのItemsControlは、Itemsコレクション プロパティに任意の型の子要素を設定することができるため、コントロールの「外観」を自由に変更できる。

***複数のパネルに纏めた複数のコンテンツ要素を格納 [#u9bc4c88]
ItemsControlのItemsコレクション プロパティへは、複数のコンテンツを追加できる。~
以下、ListBoxコントロールを例にしてItemsコレクション プロパティへ子要素の設定する例を示す。

#ref(ItemsControl.png,left,nowrap,レンダリング結果)

-複数のパネルに纏めた複数のコンテンツ要素を格納
 <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>

-Itemsコレクション プロパティに子要素を設定する場合は、~
innerText・innerXMLを使用する「[[プロパティ要素構文>#fa957fd3]]」を使用する。
-また、この際に<Object.Items>タグは省略することもできる。

-ちなみに、上記を「データ バインディング」で実装することもできる。~
これについては、「[[データ バインディングの基礎>#bbd76ce0]]」を参照のこと。

*リソース [#ea30adb6]
**リソースの定義 [#l529fcbc]
**リソースの定義と参照 [#e615c6b1]

*データ バインディング [#e915d7ec]
**データ バインディングの基礎 [#bbd76ce0]
**リソースとのデータ バインディング [#ac5a7f33]

*レイアウト [#s77734ce]
**レイアウトのプロパティ [#j27354fe]
**パネルの種類と使い方 [#v124ba4f]

*スタイルとテンプレート [#q002601b]
**スタイル [#fa989262]
**テンプレート [#bb58b780]

*トリガ [#bbe9b16b]
**プロパティ トリガ [#ce79c6df]
**データ トリガ [#i5478c0f]
**イベント トリガ [#mb5243c8]

*その他 [#a8b33d4f]
**ビルティング ブロック クラス [#y720ef3a]
***Applicationオブジェクト [#bbdb37e4]
***Window画面 [#v51c2bf3]
***ナビゲーション フレームワーク [#f6820b24]
***Win32ダイアログ [#i5cf4c80]

**入力支援 [#h12b43f1]
***メニュー・タスクバーとコマンド [#c6479c52]
***ツールチップ [#i36d28e8]
***IME制御 [#n5902de4]

**デザイナ向け機能 [#y6378ada]
***様々なシェイプ [#s897a95f]
***グラデーション [#rc7056eb]
***トランスフォーム処理 [#h9e7aefe]
***アニメーション [#d0b80558]

**MVVMデザイン パターン [#u05bda3c]
**バリデーション [#w1cd4016]
***単項目のバリデーション [#k0141195]
***一覧のバリデーション [#x358d4f2]
***フォーカス制御 [#we3801e7]
***注意事項 [#ae4315b1]

*XAMLのサンプル [#w4e8eae9]
**[[WPFのサンプル>http://opentouryo.osscons.jp/index.php?Github%E4%B8%8A%E3%81%AE%E6%88%90%E6%9E%9C%E7%89%A9#g0ce9c8a]] [#d3fbfc29]

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS