XAMLの書き方(1)
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
単語検索
|
最終更新
|
ヘルプ
]
開始行:
「[[マイクロソフト系技術情報 Wiki>http://techinfoofmicros...
-[[戻る>XAML]]
--XAMLの書き方(1)
--[[XAMLの書き方(2)]]
* 目次 [#i78ae0d5]
#contents
*概要 [#d37660b8]
基本的なXAMLの書き方。
*名前空間 [#x46c4d22]
XAMLにおける各種の名前空間の宣言は、xmlns属性を使用したXM...
ここでは、以下の既定の名前空間の宣言を例にとって説明する。
-名前空間の宣言
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-XML名前空間の簡単な説明~
http://www.kanzaki.com/docs/sw/names.html
**WPF名前空間 [#u9e59dba]
2行目のXML名前空間の宣言(xmlns="http://schemas.microsoft...
WPFフレームワーク(PresentationFramework.dll)のアセンブ...
CLR名前空間(System.Windows.Controls、System.Windows.Data...
そのため、既定でXAMLからWPFフレームワークのCLRオブジェク...
**XAML名前空間 [#f7e47ba4]
3行目のXML名前空間の宣言(xmlns:x="http://schemas.microso...
URIにマップされた共通的なXAMLの言語機能がXML名前空間(x)...
これにより、「x:」というプレフィックスを使用することで、...
**CLR名前空間 [#b9a3d659]
CLR名前空間について以下を例にとって説明する。
***(1) [#j611ebcc]
-CLR名前空間の宣言
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
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....
http://msdn.microsoft.com/ja-jp/library/system.windows.ma...
なお、XML名前空間には一意の名前を自由に付与でき(上記の例...
このプレフィックスを使用することで、XAMLからUIコンポーネ...
***(2) [#y81abbb2]
この他に、URIとしてCLR名前空間とアセンブリを直接指定する...
-CLR名前空間の宣言
xmlns:sys="clr-namespace:(CLR名前空間);assembly=(アセ...
--例1:サードパーティ製品
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:igDP="clr-namespace:Infragistics.Windows.DataPre...
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/pr...
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/pr...
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名前空間を指定する場合は、「asse...
--XML名前空間には一意の名前を自由に付与でき、このプレフィ...
-製品並みのカスタムのUIコントロールを開発・使用するなどの...
--一般的には「clr-namespace、assembly」の定義済みトークン...
--ただし、この方法は、1つのCLR名前空間に対して、1つのXM...
--(XmlnsDefinitionアセンブリ属性を使用すると、1つのXML...
***参考 [#v51c1b09]
-MSDN > WPFの基礎 > WPFのXAML > XAML名前空間およびWPF XAM...
http://msdn.microsoft.com/ja-jp/library/ms747086.aspx
*言語機能 [#ad009a58]
XAMLの言語機能である
-「[[ディレクティブ>#j78f478c]]」
-「[[マークアップ拡張>#b565ab69]]」
について説明する。
-MSDN > .NET Framework XAMLサービスの概念説明のドキュメン...
http://msdn.microsoft.com/ja-jp/library/ms753327.aspx
**ディレクティブ [#j78f478c]
XAMLの言語機能が提供する各種ディレクティブについて説明す...
|項番|ディレクティブ|説明|h
|~|~|例|h
|1|x:Class|XAML上から分離クラス(コード ビハインド)のク...
|~|~|<Window x:Class="WpfApplication1.Window1"|
|2|x:Subclass|パーシャル クラスをサポートしない言語で使用...
|~|~|-|
|3|x: ClassModifier|クラスのアクセスレベルを変更する。通...
|~|~|-|
|4|x:Code|XAML上にインラインコードを実装する場合に使用す...
|~|~|<Grid>&br; <x:Code>&br; ...
|5|x:FieldModifier|プロパティのアクセスレベルを変更する。...
|~|~|-|
|6|x:Key|XAMLで定義された各種「[[リソース>#p50dd8ac]]」を...
|~|~|<Window.Resources>&br; <Style x:Key=...
|7|x:Name|XAMLで生成したCLRオブジェクトに名前を付与する。...
|~|~|<Button x:Name="button1">&br; ...
|8|x:Shared|静的な[[リソース>#p50dd8ac]]を、取得の度に生...
|~|~|-|
|9|x:TypeArguments|ジェネリックの型引数をコンストラクタに...
|~|~|<!-- XAML 2009 -->&br;<ObservableColl...
|10|x:Uid|ローカライゼーションのプロセスとツールによって...
|~|~|-|
|11|xml:lang|カルチャ情報を宣言する。|
|~|~|<Window x:Class="WpfApplication1.Window1"&br;&n...
-MSDN > Windows Presentation Foundation > グローバライズ...
http://msdn.microsoft.com/ja-jp/library/ms745650.aspx
**マークアップ拡張 [#b565ab69]
XAMLの言語機能が提供する各種「マークアップ拡張」について...
通常、「マークアップ拡張」は、「{」と「}」の2つの中括弧...
-MSDN > WPFの基礎 > WPFのXAML
--> マークアップ拡張機能とWPF XAML~
http://msdn.microsoft.com/ja-jp/library/ms747254.aspx
--> WPF XAML拡張機能~
http://msdn.microsoft.com/ja-jp/library/ms747180.aspx
***XAMLで定義されたマークアップ拡張 [#ld42b6a9]
以下、XAMLの機能である「XAMLで定義されたマークアップ拡張...
これらの種類は、中括弧+「x:」プレフィックスの直後の文字...
-XAMLに実装されたマークアップ拡張
|項番|文字列トークン|説明|h
|~|~|例|h
|1|x:Static|静的プロパティ(定数、静的プロパティ、フィー...
|~|~|<Button &br; Foreground=...
|2|x:Null|CLRオブジェクトのプロパティにnull値を設定する(...
|~|~|<Button x:Name="button1" Background="{x:Nu...
|3|x:Type|CLRクラスの型情報を指定する。|
|~|~|詳しくは、下記、項番4の例を参照のこと。|
|4|x:Array|IEnumerableを持つArrayオブジェクト(配列)を生...
|~|~|<Window.Resources>&br; <x:Array x:Ke...
※ x:Arrayは、例外的に中括弧と共に使用しない。
***WPF固有のマークアップ拡張 [#dbf77234]
以下、WPF の機能である「WPF固有のマークアップ拡張」を一覧...
こちらは、プロパティ値に「[[データ バインディング>#w4afa3...
-XAMLに実装されたマークアップ拡張
|項番|文字列トークン|説明|h
|~|~|構文 ※ 「[[プロパティ属性構文>#tb0bd2e6]]」と「[[プ...
|1|{Binding&br;・・・|Bindingオブジェクトに「バインディン...
|~|~|具体例は、「[[データ バインディングの基礎>#h0ae3316]...
|2|{StaticResource&br;・・・|既に定義された[[リソース>#p5...
|~|~|具体例は、「[[リソースとのデータ バインディング>#eb8...
|3|{DynamicResource&br;・・・|[[リソース>#p50dd8ac]]が変...
|~|~|具体例は、「[[リソースとのデータ バインディング>#eb8...
|4|{TemplateBinding&br;・・・|親コントロールに適用したプ...
|~|~|具体例は、「[[テンプレート>#o64ea160]]」を参照のこと...
|5|{RelativeSource&br;・・・|Binding.RelativeSourceを指定...
|~|~|具体例は、[[次>#b35e6e76]]を参照のこと。&br;&br;[[プ...
|6|{ThemeDictionary&br;・・・|カスタム コントロールの作成...
|~|~|-|
※ keyには、x:Keyディレクティブによって指定された既存の[[...
**マークアップ拡張の例 [#xa799e4b]
***バインディングのマークアップ拡張の例 [#vec851f2]
[[こちら>#ca5673d9]]
***TemplateBindingの例 [#hee73def]
[[こちら>#wc88b865]]
***RelativeSourceの例 [#b35e6e76]
[[こちら>#wc88b865]]
*プロパティの設定方法 [#ra4d77a1]
プロパティの設定方法として、
-[[プロパティ属性構文>#tb0bd2e6]]:~
要素の属性にテキストを使用して設定する。
-[[プロパティ要素構文>#s389a559]]:~
要素のinnerText・innerXMLを使用してプロパティを設定する。
の2つの構文について説明する。
以下、TextBox要素に対して、同等の属性を設定する~
「[[プロパティ属性構文>#tb0bd2e6]]」と「[[プロパティ要素...
**プロパティ属性構文 [#tb0bd2e6]
要素の属性にテキストを使用してプロパティを設定する方法
-プロパティ属性構文の例
<TextBox
Width = "100"
FontSize = "30"
Text = "text1"
Background = "White"
Foreground = "Blue" />
**プロパティ要素構文 [#s389a559]
要素の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>
なお、子要素のコレクションを設定する「[[プロパティ要素構...
-Panel.Childrenプロパティ
-ItemsControl.[[Itemsプロパティ>#v7960713]]
などは、暗黙的に使用されるため明記が不要のものもある。
**型コンバータ [#r36d6abd]
XAMLパーサは、XAMLの「[[プロパティ属性構文>#tb0bd2e6]]」...
プリミティブ型に変換できるリテラル文字列として解釈するか...
なお、「型コンバータ」(と、そのベース クラスであるTypeCo...
.NETのコンポーネントとコントロールのデザイン時・実行時の...
しかし、XAMLの「[[プロパティ属性構文>#tb0bd2e6]]」からのC...
XAMLパーサは通常、プロパティの型(CLRクラス)にTypeConver...
付与されている場合は、この属性値に基づいた「型コンバータ...
以下は、ユーザ コントロールに、MyPointというカスタムの型...
XAMLの「[[プロパティ属性構文>#tb0bd2e6]]」として指定され...
***カスタム型 [#p2ae99f0]
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; }
}
}
***型コンバータ [#k0c10e95]
/// <summary>カスタム型の型コンバータ</summary>
public class MyPointConverter : TypeConverter {
/// <summary>CanConvertFrom(変換可能かチェックする)<...
public override bool CanConvertFrom(
ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <summary>指定された文字列をカスタム型(MyPoint)に...
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)を文字列に...
public override object ConvertTo(ITypeDescriptorContex...
CultureInfo culture, object value, Type destinationT...
if (destinationType == typeof(string)) {
return ((MyPoint)value).X + "," + ((MyPoint)value)...
}
return base.ConvertTo(context, culture, value, desti...
}
}
***ユーザ コントロール [#gc3459c6]
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; }
}
・・・
***型コンバータの使用例 [#gc5dd259]
上記のユーザ コントロールのカスタムの型を取るCLRプロパテ...
<uc:UserControl1 x:Name="userControl1" MyLocation="10,20...
ただし、(当然ながら、)文字列からの変換をサポートしている...
文字列で表現できないプロパティ値は、「[[プロパティ属性構...
-MSDN > WPFの基礎 > WPFのXAML > TypeConverters及びXAML~
http://msdn.microsoft.com/ja-jp/library/aa970913.aspx
*コンテンツ構文 [#m4c088a5]
「コンテンツ構文」とは、[[Contentプロパティ>#gc84bde8]](...
-ContentPropertyAttributeを付けることで、
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.ma...
---[ContentPropertyAttribute("Content")] → [[Contentプロ...
---[ContentPropertyAttribute("Items")] → [[Itemsプロパテ...
-属性に指定される[[Contentプロパティ>#gc84bde8]]を、~
innerText・innerXML([[プロパティ要素構文>#s389a559]])と...
--コンテンツ構文
---[[プロパティ属性構文>#tb0bd2e6]]
<Button Content="Click Here" />
---[[プロパティ要素構文>#s389a559]]
<Button>Click Here</Button>
-比較
--なお、[[Windows Forms]]や[[Web Forms>ASP.NET Web Forms]...
UIコントロールの「[[スタイル>#v30d5ab6]]」属性の指定によ...
--これに対し、WPFのUIコントロールは「[[スタイル>#v30d5ab6...
[[Contentプロパティ>#gc84bde8]](または[[Itemsプロパティ>...
コントロールの「外観」を自由に変更でき、柔軟性が非常に高...
-補足:Windowsフォームの外観の変更
--コントロールを自前で描画する「オーナー描画」と呼ばれる...
「オーナー描画」はグラフィックス メソッドなどを使用して、~
すべての描画を独自に行わなければならないため、深い知識と...
--関連資料
---[[.NETコントロールのカスタマイズ方法]]
**Contentプロパティ [#gc84bde8]
WPFのContentControlは、
-ContentControl.Contentプロパティに設定された単一の要素を...
-ContentControl.Contentプロパティに任意の型の子要素を設定...
-従って、ContentControlを継承するButtonクラスやLabelクラ...
--Control.Templateプロパティ
--ContentControl.ContentTemplateプロパティ
***文字列のコンテンツ要素を格納 [#m12672f2]
WPFのContentControlのButtonコントロールを例にしてContent...
-XAML
--[[プロパティ属性構文>#tb0bd2e6]]:
<Button Width="200" Height="200" Content="ボタン"/>
--[[プロパティ要素構文>#s389a559]]:
<Button Width="200" Height="200">ボタン</Button>
-レンダリング結果
#ref(ContentString.png,left,nowrap,文字列のコンテンツ要素...
***イメージのコンテンツ要素を格納 [#faf81a9f]
Contentプロパティには、Imageオブジェクトなどの任意の型の...
-XAML
<Button Width="200" Height="200">
<Button.Content>
<Image Source=".\Blue hills.jpg"/>
</Button.Content>
</Button>
-レンダリング結果
#ref(ContentImage.png,left,nowrap,イメージのコンテンツ要...
***パネルに纏めて格納した複数のコンテンツ要素 [#a73fa28e]
-XAML
--2つ以上の要素を設定したい場合は、パネル要素を使用する。
<Button Width="200" Height="200">
<Button.Content>
<StackPanel Orientation="Vertical">
<Image Source=".\Blue hills.jpg" Margin="5" />
<TextBlock Text="ボタン" HorizontalAlignment="Cent...
</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...
</StackPanel>
</Button>
-レンダリング結果
#ref(ContentStringAndImage.png,left,nowrap,パネルに纏めて...
**Itemsプロパティ [#v7960713]
WPFのItemsControlは、Itemsプロパティに任意の型の子要素を...
***複数のパネルに纏めて格納した複数のコンテンツ要素 [#w0e...
ItemsControlのItemsプロパティへは、複数のコンテンツを追加...
以下、ListBoxコントロールを例にしてItemsプロパティへ子要...
-XAML
<Grid>
<ListBox>
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Source=".\Blue hills.jpg" Height="100"/>
<TextBlock Text="Blue hills" VerticalAlignment="...
</StackPanel>
</Border>
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Source=".\Sunset.jpg" Height="100"/>
<TextBlock Text="Sunset" VerticalAlignment="Cent...
</StackPanel>
</Border>
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Source=".\Water lilies.jpg" Height="100"/>
<TextBlock Text="Water lilies" VerticalAlignment...
</StackPanel>
</Border>
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Source=".\Winter.jpg" Height="100"/>
<TextBlock Text="Winter" VerticalAlignment="Cent...
</StackPanel>
</Border>
</ListBox>
</Grid>
-レンダリング結果
#ref(ItemsControl.png,left,nowrap,複数のパネルに纏めて格...
-説明
--Itemsプロパティに子要素を設定する場合は、~
innerText・innerXMLを使用する「[[プロパティ要素構文>#s389...
---また、この際に<Object.Items>タグは省略することもできる。
--ちなみに、上記を「[[データ バインディング>#w4afa32c]]」...
---これについては、「[[データ バインディングの基礎>#h0ae3...
*リソース [#p50dd8ac]
ここでは、
-「リソース」の定義方法と、
-前述の各「[[マークアップ拡張>#b565ab69]]」を使用し、~
プロパティ値に「リソース」への参照を指定する方法
について説明する。
※「リソース」の「[[データ バインディング>#w4afa32c]]」に...
「[[リソースとのデータ バインディング>#eb81566f]]を参照の...
-参考
--MSDN > WPFの基礎 > リソース~
http://msdn.microsoft.com/ja-jp/library/ms742538.aspx
**リソースの定義 [#g7e2fd50]
「リソース」とは、ResourceDictionary 型のオブジェクトであ...
-ApplicationオブジェクトのResources プロパティ
-各UI要素(FrameworkElement or FrameworkContentElement)...
に「[[プロパティ要素構文>#s389a559]]」を使用して定義でき...
-MSDN > .NET Frameworkクラス ライブラリ
-- > System.Windows.ResourceDictionaryクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.re...
-- > System.Windows.Application.Resourcesプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.ap...
-- > System.Windows.FrameworkElement.Resourcesプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.fr...
-- > System.Windows.FrameworkContentElement.Resourcesプロ...
http://msdn.microsoft.com/ja-jp/library/system.windows.fr...
このため、任意のUI要素に定義可能であるが、~
通常はルート要素(Window or Page)上に定義する。~
また、「リソース」は、定義場所により以下のような呼称・特...
***リソースの定義場所 [#qe6a5b64]
-アプリケーション リソース~
ApplicationオブジェクトのResourcesプロパティに定義された...
「アプリケーション リソース」と呼び、全体から(つまりどこ...
-ウィンドウ ページ リソース~
Window・PageオブジェクトのResourcesプロパティに定義された...
「アプリケーション リソース」と呼び、そのWindow・Pageと、...
-イミディエイト リソース~
各UI要素(FrameworkElement or FrameworkContentElement)の~
Resourcesプロパティに定義された「リソース」を「イミディエ...
「リソース」を定義した要素と、その子要素から参照できると...
***リソースの定義例 [#sedc736a]
-「リソース」には、前述のx:Key ディレクティブを使用して一...
<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>
>※ 先頭で、String型のインポートが必要~
xmlns:sys="clr-namespace:System;assembly=mscorlib"
-補足:ジェネリック コレクションのリソース~
ジェネリック コレクションを「リソース」に定義するには、x:...
ObservableCollection<T>コレクション クラスなどのジェネリ...
これは、XAML2009 からのサポートとなる。
***リソースの使用方法 [#r6badd32]
「リソース」を定義したら、各種「[[マークアップ拡張>#b565a...
プロパティ値に「[[データ バインディング>#w4afa32c]]」や、...
この時、参照する側からx:Key ディレクティブを使用して割り...
なお、「[[スタイル>#v30d5ab6]]」や「[[テンプレート>#o64ea...
指定の型のオブジェクトに「[[スタイル>#v30d5ab6]]」や「[[...
これについては、「[[スタイルとテンプレート>#j0c577be]]」...
-MSDN > .NET Frameworkクラス ライブラリ
-- > System.Windows.Style.TargetType プロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.st...
-- > System.Windows.Controls.ControlTemplate.TargetTypeプ...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
**リソースの定義と参照 [#wd960230]
以下、「リソース」の定義と、プロパティ値に「リソース」へ...
***StaticResource参照の例 [#ybb9b94a]
StaticResource参照では、
-コンパイル時に「リソース」検索が行われ、各「リソース」に...
-「リソース」検索により、「リソース」が発見できなかった場...
以下は、StaticResourceの定義と参照例。
-XAML
--StaticResourceの定義と参照例(1)
---以下は、「[[マークアップ拡張>#b565ab69]]」を使用して、...
---また、属性名を省略すると自動的にコンストラクタに渡され...
ResourceKey属性に指定の値を渡す旨を指示する「ResourceKey=...
>
<Window.Resources>
<SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
</Window.Resources>
<Grid>
<Ellipse Fill="{StaticResource ResourceKey=BlueBrush}"...
</Grid>
>↓ 「ResourceKey =」という記述を省略
>
<Window.Resources>
<SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
</Window.Resources>
<Grid>
<Ellipse Fill="{StaticResource BlueBrush}" Height="150...
</Grid>
--StaticResourceの定義と参照例(2)~
以下は、一般的ではないが「[[プロパティ要素構文>#s389a559]...
なお、WPFのみ、StaticResource参照を「[[プロパティ要素構文...
<Window.Resources>
<SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
</Window.Resources>
<Grid>
<Ellipse Height="150" Width="150">
<Ellipse.Fill>
<StaticResource ResourceKey="BlueBrush"/>
</Ellipse.Fill>
</Ellipse>
</Grid>
-レンダリング結果
#ref(StaticResource.png,left,nowrap,StaticResourceの定義...
***DynamicResource参照の例 [#h04a05da]
-DynamicResource参照では、アプリケーションの起動時に、~
後で「リソース」検索を行う際に使用する一時的な式が作成さ...
アプリケーションの実行後、「リソース」が必要になった際に...
-このためDynamicResource参照は、
--主に「リソース」の値が変更される場合、StaticResource参...
--「リソース」検索により、「リソース」が発見できなかった...
-なお、DynamicResource参照は、WPFでのみ利用可能で、「Silv...
以下は、DynamicResourceの定義と参照例。
-以下は、リソースがアプリケーション外部から変更される場合...
以下は、デスクトップ画面のテーマの変更(Windows XP → Wind...
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Ellipse Grid.Row="0"
Fill="{StaticResource ResourceKey={x:Static SystemCo...
<Ellipse Grid.Row="1"
Fill="{DynamicResource ResourceKey={x:Static SystemC...
</Grid>
#ref(DynamicResource1.png,left,nowrap,DynamicResourceの定...
-以下は、リソースがアプリケーション内部から変更される場合...
以下は、アプリケーションからの「リソース」の動的な変更を...
なお、「リソース」の動的な変更は、FrameworkElement.Resour...
--XAML
<Window.Resources>
<SolidColorBrush x:Key="MyBrush" Color="Blue"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition Height="23"/>
</Grid.RowDefinitions>
<Ellipse Grid.Row="0" Fill="{StaticResource MyBrush}"/>
<Ellipse Grid.Row="1" Fill="{DynamicResource MyBrush}"/>
<StackPanel Grid.Row="2" Orientation="Horizontal" Hori...
<Button Content="青" Height="23" Name="button1" Widt...
<Button Content="赤" Height="23" Name="button2" Widt...
</StackPanel>
</Grid>
--コード ビハインド
private void button1_Click(object sender, RoutedEventArg...
this.Resources["MyBrush"] = Brushes.Blue;
}
private void button2_Click(object sender, RoutedEventArg...
this.Resources["MyBrush"] = Brushes.Red;
}
#ref(DynamicResource2.png,left,nowrap,DynamicResourceの定...
***StaticResource参照 + ディクショナリ ファイルの例 [#k80...
ResourceDictionaryは、「ディクショナリ ファイル」に定義す...
「ディクショナリ ファイル」を追加する際は、
+プロジェクト ファイルを右クリックし、
+[追加] → [リソース ディクショナリ]を選択するか、~
[追加] → [新しい項目]を選択し、表示される[[テンプレート>#...
#ref(AddDictionary.png,left,nowrap,ディクショナリ ファイ...
-前述のStaticResource参照の例を、~
「ディクショナリ ファイル」を使用するように書き直した例を...
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
</ResourceDictionary>
''ディクショナリ ファイルの定義例 (Dictionary1.xaml)''
-「ディクショナリ ファイル」を「イミディエイト・リソース...
<Window.Resources>
<ResourceDictionary Source="Dictionary1.xaml"/>
</Window.Resources>
<Grid>
<Ellipse Fill="{StaticResource BlueBrush}" Height="150...
</Grid>
>
#ref(StaticResourceAndDictionary.png,left,nowrap,StaticRe...
''StaticResource参照 + ディクショナリ ファイルの使用例''
***DynamicResource参照 + ディクショナリ ファイルの例 [#z0...
-DynamicResource参照とResourceDictionaryを組み合わせ、
-ResourceDictionaryを、Application.LoadComponentで動的に...
-Application.Current.Resourcesに設定することにより、
-「[[スタイル>#v30d5ab6]]」(スキン )などの設定をアプリ...
以下の、その例を示す。
-Dictionary
--Dictionary1.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="MyBrush" Color="Blue"/>
</ResourceDictionary>
--Dictionary2.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="MyBrush" Color="Red"/>
</ResourceDictionary>
-XAML
<StackPanel>
<Ellipse Fill="{DynamicResource MyBrush}" Height="150"...
<Button Content="青" Height="23" Name="button1" Width=...
<Button Content="赤" Height="23" Name="button2" Width=...
</StackPanel>
-コード ビハインド
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
this.LoadResourceDictionary("Dictionary1.xaml");
}
private void button1_Click(object sender, RoutedEventA...
this.LoadResourceDictionary("Dictionary1.xaml");
}
private void button2_Click(object sender, RoutedEventA...
this.LoadResourceDictionary("Dictionary2.xaml");
}
private void LoadResourceDictionary(string name) {
ResourceDictionary dictionary =
(ResourceDictionary)Application.LoadComponent(new ...
if (dictionary != null) Application.Current.Resource...
}
}
>
#ref(DynamicResourceAndDictionary.png,left,nowrap,Dynamic...
''DynamicResource参照 + ディクショナリ ファイルの使用例''
*データ バインディング [#w4afa32c]
様々なソースと「データ バインディング」するサンプルを示す。
なお、サンプルのXAMLソースを読むためには、以下の、~
Bindingプロパティの設定方法を理解しておく必要がある。
''Bindingプロパティの設定方法''
|項番|プロパティ|説明|h
|1|Mode|OneTime、OneWay、TwoWay のいずれかの「バインディ...
|2|Source|「バインディング ソース」を指定する。「バイン...
|3|ElementName|UI要素名を使用して「バインディング ソース...
|4|[[RelativeSource>#b35e6e76]]|「バインディング ターゲ...
|5|Path|「バインディング ソース」のプロパティ名を指定す...
|6|XPath|「バインディング ソース」として、XMLデータソー...
|7|TargetNullValue|ソース値が null のときに返される値を...
|8|Converter|「[[値コンバータ>WPFのアーキテクチャ#nf7e2b...
|9|ConverterCulture|「[[値コンバータ>WPFのアーキテクチャ...
|10|ConverterParameter|「[[値コンバータ>WPFのアーキテクチ...
-MSDN > ・・・ > バインディングのマークアップ拡張機能~
http://msdn.microsoft.com/ja-jp/library/ms750413.aspx
--MSDN > ・・・ > PropertyPathのXAML構文~
http://msdn.microsoft.com/ja-jp/library/ms742451.aspx
--MSDN > ・・・ > 方法:XMLDataProviderとXPathクエリを試...
http://msdn.microsoft.com/ja-jp/library/ms749287.aspx
**データ バインディングの基礎 [#h0ae3316]
以下、「[[WPFのアーキテクチャ - データ バインディング>WPF...
***コード ビハインドからのデータ バインディング(モード:...
-モード:OneWayの「データ バインディング」を行う。
-「データ バインディング」の基本的な動作を理解するために、
--Bindingオブジェクトをコード ビハインドで自作し、
--以下の2つのオブジェクトを結びつける。
---「バインディング ソース」
---「バインディング ターゲット」
-XAML
<StackPanel
x:Name="MainPanel"
Loaded="MainPanel_Loaded">
<TextBlock x:Name="TextBlock1"/>
<TextBlock x:Name="TextBlock2"/>
</StackPanel>
-コード ビハインド
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
}
private void MainPanel_Loaded(object sender, RoutedEve...
{
// バインディング ソース(Person)
Person BindingSource =
new Person() { Height = 1.7, Weight = 60 };
// Bindingオブジェクトによりバインド
// HeightプロパティをOneWayでバインド
Binding BindingHeight = new Binding("Height");
BindingHeight.Mode = BindingMode.OneWay;
// バインディング ソース(Person)
BindingHeight.Source = BindingSource;
// バインディング ターゲット(TextBlock)
TextBlock1.SetBinding(TextBlock.TextProperty, Bindin...
// WeightプロパティをOneWayでバインド
Binding BindingWeight = new Binding("Weight");
BindingWeight.Mode = BindingMode.OneWay;
// バインディング ソース(Person)
BindingWeight.Source = BindingSource;
// バインディング ターゲット(TextBlock)
TextBlock2.SetBinding(TextBlock.TextProperty, Bindin...
}
}
/// <summary>バインディング ソース(Person)</summary>
public class Person {
public double Height { get; set; }
public double Weight { get; set; }
}
***コード ビハインドからのDataContextを使用したデータ バ...
上記のMainPanel_Loadedメソッドのコードを一部編集し、MainP...
FrameworkElement.DataContextプロパティに「バインディング ...
Bindingオブジェクトへの「バインディング ソース」の指定が...
-コード ビハインド
private void MainPanel_Loaded(object sender, RoutedEvent...
// バインディング ソース(Person)
MainPanel.DataContext =
new Person() { Height = 1.7, Weight = 60 };
// Bindingオブジェクトによりバインド
// HeightプロパティをOneWayでバインド
Binding BindingHeight = new Binding("Height");
BindingHeight.Mode = BindingMode.OneWay;
// バインディング ターゲット(TextBlock)
this.TextBlock1.SetBinding(TextBlock.TextProperty, Bin...
// WeightプロパティをOneWayでバインド
Binding BindingWeight = new Binding("Weight");
BindingWeight.Mode = BindingMode.OneWay;
// バインディング ターゲット(TextBlock)
TextBlock2.SetBinding(TextBlock.TextProperty, BindingW...
}
***BindingオブジェクトをXAMLで実装する([[プロパティ要素...
-BindingオブジェクトをXAMLのマークアップ機能で実装する。~
更に、XAMLのマークアップ機能を使用して、Bindingオブジェク...
上記のXAMLとMainPanel_Loadedメソッドのコードを一部編集し...
--XAML
<StackPanel
x:Name="MainPanel"
Loaded="MainPanel_Loaded">
<TextBlock>
<TextBlock.Text>
<Binding Path="Height" Mode="OneWay"/>
</TextBlock.Text>
</TextBlock>
<TextBlock>
<TextBlock.Text>
<Binding Path="Weight" Mode="OneWay"/>
</TextBlock.Text>
</TextBlock>
</StackPanel>
--コード ビハインド
private void MainPanel_Loaded
(object sender, RoutedEventArgs e) {
// バインディング ソース(Person)
MainPanel.DataContext =
new Person() { Height = 1.7, Weight = 60 };
}
***Bindingオブジェクトをバインディングのマークアップ拡張...
-一般的には、「データ バインディング」を実装する場合、XAM...
「バインディングのマークアップ拡張」により「[[プロパティ...
-上記のXAMLを「バインディングのマークアップ拡張」を使用し...
<StackPanel x:Name="MainPanel" Loaded="MainPanel_Loaded">
<TextBlock Text="{Binding Path=Height, Mode=OneWay}" />
<TextBlock Text="{Binding Path=Weight, Mode=OneWay}" />
</StackPanel>
-また、属性名を省略すると自動的にコンストラクタに渡される...
(Path属性に指定の値を渡す旨を指示する)「Path=」という記...
<StackPanel x:Name="MainPanel" Loaded="MainPanel_Loaded">
<TextBlock Text="{Binding Height, Mode=OneWay}" />
<TextBlock Text="{Binding Weight, Mode=OneWay}" />
</StackPanel>
***変更通知の追加(モード:OneWay or OneWayToSource) [#i...
下記は、モード:OneWay or OneWayToSourceを併用した「デー...
この例では、「バインディング ソース」のプロパティ値の変更...
なお、この際、「バインディング ソース」は、INotifyPropert...
-XAML
<StackPanel x:Name="MainPanel" Loaded="MainPanel_Loaded">
<TextBox Margin="10" Text="{Binding Height, Mode=OneWa...
<TextBox Margin="10" Text="{Binding Weight, Mode=OneWa...
<Button Margin="10" Content="計算" Click="Button_Click...
<TextBlock Margin="10" Text="{Binding Bmi, Mode=OneWay...
</StackPanel>
-コード ビハインド
/// <summary>/// Window1.xaml の相互作用ロジック/// </su...
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
}
/// <summary>初期化イベント</summary>
private void MainPanel_Loaded(object sender, RoutedEve...
// バインド ソース(Person)
MainPanel.DataContext = new Person();
}
/// <summary>計算イベント</summary>
private void Button_Click(object sender, RoutedEventAr...
((Person)MainPanel.DataContext).Calculate();
}
}
-バインディングソース
/// <summary>バインド ソース(Person)</summary>
public class Person : INotifyPropertyChanged {
public double Height { get; set; }
public double Weight { get; set; }
double _bmi;
public double Bmi {
get { return this._bmi; }
set {
this._bmi = value;
// 変更通知
this.OnPropertyChanged("Bmi");
}
}
/// <summary>計算処理</summary>
public void Calculate() {
this.Bmi = Weight / Math.Pow(Height, 2);
}
#region INotifyPropertyChanged メンバ
/// <summary>値変更イベントの定義</summary>
public event PropertyChangedEventHandler PropertyChang...
/// <summary>変更通知(値変更イベントを発生させる)</s...
protected virtual void OnPropertyChanged(string proper...
PropertyChangedEventHandler handler = this.PropertyC...
if (handler != null)
handler(this, new PropertyChangedEventArgs(propert...
}
#endregion
}
***値コンバータを使用したデータ バインディング(モード:O...
続いて、上記処理に、BMI(肥満度)プロパティが
-18.5未満の場合、出力先のTextBlockの背景色を青色に
-25以上の場合、出力先のTextBlockの背景色を赤色に
変更する処理を追加する。
これには別途、背景色プロパティを定義することで実現するこ...
ここでは、前述のIValueConverterインターフェイスを実装した...
値の変換処理は、「値コンバータ」のConvertメソッドに実装す...
-XAML
<Window.Resources>
<my:BmiLevelConverter x:Key="bmiLevelConverter"/>
</Window.Resources>
<StackPanel x:Name="MainPanel" Loaded="MainPanel_Loaded">
<TextBox Margin="10" Text="{Binding Height, Mode=OneWa...
<TextBox Margin="10" Text="{Binding Weight, Mode=OneWa...
<Button Margin="10" Content="計算" Click="Button_Click...
<TextBlock Margin="10"
Text="{Binding Bmi, Mode=OneWay}"
Background="{Binding Bmi, Mode=OneWay,
Converter={StaticResource bmiLevelConverter}}"/>
</StackPanel>
-値コンバータ
/// <summary>BMIレベルに合った背景色を返す</summary>
public class BmiLevelConverter : IValueConverter {
#region IValueConverter メンバ
/// <summary>変換メソッド(ソースからターゲット)</sum...
public object Convert(object value, Type targetType, o...
// BMIレベルに合った背景色を返す
double target = (double)value;
SolidColorBrush level;
if (target < 18.5)
level = new SolidColorBrush(Colors.Blue);
else if (target > 25)
level = new SolidColorBrush(Colors.Red);
else
level = new SolidColorBrush(Colors.White);
return level;
}
/// <summary>変換メソッド(ターゲットからソース)</sum...
public object ConvertBack(object value, Type targetTyp...
throw new NotImplementedException();
}
#endregion
}
***INotifyPropertyChangedの変更通知を「依存関係プロパティ...
なお、変更通知は、INotifyPropertyChangedインターフェイス...
上記の例のBMI(肥満度)プロパティを「依存関係プロパティ」...
-バインディングソース
/// <summary>バインド ソース(Person)</summary>
public class Person : DependencyObject {
public double Height { get; set; }
public double Weight { get; set; }
/// <summary>Bmiプロパティを依存関係プロパティとして登...
public static readonly DependencyProperty BmiProperty =
DependencyProperty.Register("Bmi", typeof(double), t...
new UIPropertyMetadata(0.0));
/// <summary>BmiプロパティのCLRプロパティ</summary>
public double Bmi {
get { return (double)this.GetValue(Person.BmiPropert...
set { this.SetValue(Person.BmiProperty, value); }
}
/// <summary>計算処理</summary>
public void Calculate(){
this.Bmi = Weight / Math.Pow(Height, 2);
}
}
BMI(肥満度)プロパティが変更されると、UI要素(TextBlock...
このように、「依存関係プロパティ」は既定で変更通知をサポ...
***双方向のデータ バインディング(モード:TwoWay) [#q577...
以下の例では、モード:TwoWayの「データ バインディング」を...
2つのUI要素、TextBoxとSliderを双方向接続した例である。
なお前述のようにUI要素の表示に関するプロパティは、~
基本的に「依存関係プロパティ」として定義されており、~
既定で変更通知をサポートしている。このため、既定で双方向...
なお、「バインディング ソース」をUI要素に接続する場合は、...
-TextBox(ソース)→Slider(ターゲット)
--XAML
<StackPanel Orientation="Vertical">
<Label>TextBox</Label>
<TextBox x:Name="textBox1" Text="5"/>
<Rectangle Height="20"></Rectangle>
<Label>Slider</Label>
<Slider x:Name="Slider1"
Value="{Binding ElementName=textBox1, Path=Text, Mod...
</StackPanel>
-Slider(ソース)→TextBox(ターゲット)
--バインディング ソース、バインディング ターゲットを反転...
--すると「バインディング ターゲット」(TextBox)の変更が...
(TextBoxから、フォーカスが外れないとSliderに変更値が反映...
--これは、ほとんどの依存関係プロパティの既定値は Property...
--この場合、「バインディングのマークアップ拡張」に、「Upd...
「バインディング ターゲット」(TextBox)からの変更が直ち...
--XAML
<StackPanel Orientation="Vertical">
<Label>TextBox</Label>
<TextBox x:Name="textBox1"
Text="{Binding ElementName=Slider1, Path=Value, Mode...
<Rectangle Height="20"></Rectangle>
<Label>Slider</Label>
<Slider x:Name="Slider1" Value="5"/>
</StackPanel>
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
---UpdateSourceTriggerプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.da...
---UpdateSourceTrigger列挙体~
http://msdn.microsoft.com/ja-jp/library/system.windows.da...
***値コンバータを使用したデータ バインディング(モード:T...
双方向の値の変換に対応した「値コンバータ」は、~
Convert、ConvertBackメソッドの双方を実装する必要がある。
-XAML
<Window.Resources>
<my:ValConverter x:Key="valConverter" />
</Window.Resources>
<StackPanel Orientation="Vertical">
<Label>TextBox</Label>
<TextBox x:Name="textBox1" Text="500"/>
<Rectangle Height="20"></Rectangle>
<Label>Slider</Label>
<Slider x:Name="Slider1"
Value="{Binding ElementName=textBox1, Path=Text, Mod...
Converter={StaticResource valConverter}}"/>
</StackPanel>
-コード ビハインド
public class ValConverter : IValueConverter {
#region IValueConverter メンバ
/// <summary>変換メソッド(ソースからターゲット)</sum...
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo c...
return int.Parse(value.ToString()) / 100;
}
/// <summary>変換メソッド(ターゲットからソース)</sum...
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo c...
return ((double)value) * 100;
}
#endregion
}
***ItemsSourceへのデータ バインディング [#qe911f6c]
ItemsControlから派生した要素のItemsSource属性にコレクショ...
-ItemsSourceへのデータ バインディング(UI要素を含まない「...
以下は、ObservableCollection<T> コレクション クラスを使用...
なお、ObservableCollection<T>コレクション クラスは、INoti...
--XAML
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="listBox1" ItemsSource="{Binding}"/>
<Button Height="23" Name="button1" Click="button1_Clic...
</StackPanel>
--コード ビハインド
public partial class Window1 : Window {
ObservableCollection<string> _cities = new ObservableC...
public Window1() {
InitializeComponent();
this._cities.Add("札幌市");
this._cities.Add("仙台市");
this._cities.Add("静岡市");
this.stackPanel1.DataContext = _cities;
}
private void button1_Click(object sender, RoutedEventA...
this._cities.Add("神戸市" + this.listBox1.Items.Coun...
}
}
--UI要素を含まない「データ バインディング」の実装例につい...
---上記例では、button1_ClickイベントでItemがObservableCol...
また、この変更通知をサポートしているObservableCollection<...
Collection<T>コレクションに追加されたItemがListBoxの表示...
---なお、変更通知に対応したカスタム コレクションを作成す...
ObservableCollection<T>や、Collection<T> & INotifyCollect...
---この際の注意点としては、後者のCollection<T> & INotifyC...
Add、RemoveAtなどのメソッドに変更通知を実装し、「変更通知...
前述のPropertyChangedEventHandlerではなく、NotifyCollecti...
-ItemsSourceへのデータ バインディング(UI要素を含んだ「デ...
以下は、[[「Itemsプロパティ」>#v7960713]]の例を「データ ...
--XAML
<StackPanel x:Name="stackPanel1">
<ListBox ItemsSource="{Binding}"/>
</StackPanel>
--コード ビハインド
public Window1() {
InitializeComponent();
// バンディング ソース(コレクション)
ObservableCollection<Border> cities = new ObservableCo...
// ワーク
Border tmpBorder = null;
StackPanel tmpStackPanel = null;
Image tmpImage = null;
TextBlock tmpTextBlock = null;
// Borderの構築
tmpBorder = new Border();
tmpBorder.BorderBrush = Brushes.Black;
tmpBorder.BorderThickness = new Thickness(1);
tmpBorder.Margin = new Thickness(5);
// StackPanelの構築
tmpStackPanel = new StackPanel();
tmpStackPanel.Orientation = Orientation.Horizontal;
tmpStackPanel.Height = 120;
tmpStackPanel.Width = 250;
tmpStackPanel.Margin = new Thickness(5);
// Imageの構築
tmpImage = new Image();
tmpImage.Source=new BitmapImage(
new Uri(@".\Water lilies.jpg", UriKind.Relative));
tmpImage.Height=100;
// TextBlockの構築
tmpTextBlock = new TextBlock();
tmpTextBlock.Text="Water lilies";
tmpTextBlock.VerticalAlignment = VerticalAlignment.Cen...
// 階層構造の組み立て
tmpStackPanel.Children.Add(tmpImage);
tmpStackPanel.Children.Add(tmpTextBlock);
tmpBorder.Child = tmpStackPanel;
// バンディング ソース(コレクション)に追加
cities.Add(tmpBorder);
// ・・・(n項繰り返し)・・・
// データ バンディング
stackPanel1.DataContext = cities;
}
--UI要素を含んだ「データ バインディング」の実装例について、
---子要素を持つUI要素をコード ビハインドで作成し、これを...
---このような場合は、「[[テンプレート>#o64ea160]]」を使用...
---「[[テンプレート>#o64ea160]]」を使用した実装例は、「[[...
***インデクサによるデータ バインディング [#t27b49c9]
インデクサについても、Path属性に角括弧を指定することで接...
-XAML
<Grid>
<Image x:Name="Image1"
Height="200" Width="200"
Source="{Binding Path=[Source]}"
ToolTip="{Binding Path=[ToolTip]}"/>
</Grid>
-コード ビハインド
public Window1() {
InitializeComponent();
Hashtable ht = new Hashtable();
ht["Source"] = @".\Winter.jpg";
ht["ToolTip"] = "Winter";
this.Image1.DataContext = ht;
}
これらを応用すると、~
インデクサを持つオブジェクトの配列(反復処理をサポート)~
をデータ バインディングすることも可能であることが分かる。
ビジネス・アプリケーションでは、DataGridへDataTableをデー...
DataGridの列へDataTableの列をマッピングするようなケースで...
**[[リソース>#p50dd8ac]]とのデータ バインディング [#eb815...
「[[リソース>#p50dd8ac]]」参照を「バインディングのマーク...
***StaticResourceを使用したデータ バインディング [#q416a6...
-例えば、静的な「[[リソース>#p50dd8ac]]」を使用し、以下の...
--StaticResourceのデータ バインディング (1)
<Window.Resources>
<sys:String x:Key="val">Click Here</sys:String >
</Window.Resources>
<StackPanel>
<Button Content="{Binding Source={StaticResource val}}...
</StackPanel>
>※ 先頭で、String型のインポートが必要~
xmlns:sys="clr-namespace:System;assembly=mscorlib"
-ItemsControlから派生したUIコントロールのItemsSource属性...
「[[リソース>#p50dd8ac]]」の対象オブジェクトは反復処理を...
--StaticResourceのデータ バインディング (2)
<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 ...
</StackPanel>
>※ 先頭で、String型のインポートが必要~
xmlns:sys="clr-namespace:System;assembly=mscorlib"
***DynamicResourceを使用したデータ バインディング [#e0022...
動的な「[[リソース>#p50dd8ac]]」を使用した「データ バイン...
以下、「{Binding Source={DynamicResource」をテストした際...
型 'Binding' の 'Source' プロパティで 'DynamicResourceEx...
-参考
--MSDN > .NET Frameworkクラス ライブラリ
--- > System.Windows.Data.Binding.Sourceプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.da...
--- > System.Windows.DynamicResourceExtensionクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.dy...
*レイアウト [#lc8aa2dd]
ココでは、レイアウト方法として、
-[[レイアウトのプロパティ>#ad27e006]]
-[[パネルの種類と使い方>#t2926641]]
の2つについて説明する。
-MSDN > WPFの基礎 > レイアウト システム~
http://msdn.microsoft.com/ja-jp/library/ms745058.aspx
**レイアウトのプロパティ [#ad27e006]
-ココでは、「レイアウト」関係のプロパティについて説明する。
-これらのプロパティは、「レイアウト」機能を追加するFramew...
--配置の際、各要素間に余白を指定したい場合は、Margin、Pad...
---Margin :自要素と親要素の間
---Padding:自要素と子要素の間~
※ [left, top, right, bottom]と設定可能。省略時の動作は、...
--配置の際、「揃え」を指定したい場合は、HorizontalAlignme...
---HorizontalAlignment :水平方法の揃え(Center、Left、Ri...
---VerticalAlignment :垂直方法の揃え(Center、Top、Bot...
※ Stretchは、引き伸ばして余白を埋めて配置の意味。
-以下、「レイアウト」関係のプロパティを使用したXAMLとレン...
--XAML
<Border Background="LightBlue" BorderBrush="Black" Borde...
<StackPanel Background="White" HorizontalAlignment="Ce...
<TextBlock Margin="5,0,5,0" HorizontalAlignment="Cen...
<Button HorizontalAlignment="Left" Margin="20">Butto...
<Button HorizontalAlignment="Right" Margin="10">Butt...
<Button HorizontalAlignment="Stretch" Margin="0">But...
</StackPanel>
</Border>
--[[レンダリング>https://i-msdn.sec.s-msft.com/dynimg/IC1...
-参考
--MSDN > WPFの基礎 > 基本要素 > 配置、余白、パディングの...
http://msdn.microsoft.com/ja-jp/library/ms751709.aspx
**パネルの種類と使い方 [#t2926641]
WPFでは、パネルを使用した「レイアウト」が可能である。
-パネルには、以下のような特徴がある。
--複数のUIElementを含めることができる(UIElementCollectio...
---MSDN > .NET Frameworkクラス ライブラリ > System.Window...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
>UIElement子要素の順序付けられたコレクションを表す。~
XAMLから「[[プロパティ要素構文>#s389a559]]」の「[[コンテ...
<Panel.Children>タグを使用する(ただし、このタグを...
また、コード ビハインドから、パネル要素に子要素を追加する...
--自分に含まれるUIElementを管理する。
--パネル自体もUIElementであるため、パネルへの組み込みが可能
-使用可能なパネル要素には次のものがある。
|#|パネル名|クラス名|説明|h
|1|キャンバス パネル|Canvas|座標を使用して子要素を明示的...
|2|ドック パネル|DockPanel|パネルの各「辺」に、子要素をド...
|3|スタック パネル|StackPanel|子要素を水平方向または垂直...
|4|折り返しパネル|WrapPanel|子要素を水平方向または垂直方...
|5|(均一)グリッド パネル|UniformGrid|列と行で構成されて...
|6|グリッド パネル|Grid|列と行で構成されている柔軟なグリ...
-また、親要素であるパネルへ配置する子要素の座標などの情報...
子要素から「添付プロパティ」を使用して設定可能である。
***キャンバス パネル [#p5a51a2b]
-座標を使用して子要素を明示的に配置できる領域を定義する。
--XAML
<Canvas Background="LightSteelBlue">
<TextBlock Canvas.Top="10" Canvas.Left="20">
Hello World!
</TextBlock>
<TextBlock Canvas.Top="40" Canvas.Left="50">
絶対位置決め方式は便利ではありませんか?
</TextBlock>
</Canvas>
--レンダリング結果
#ref(RenderingResultOfCanvas.png,left,nowrap,キャンバス ...
-キャンバス パネルでは、「添付プロパティ」であるCanvas.To...
子要素から座標位置を明示的に指定・配置できるため、Windows...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***ドック パネル [#pe1b48eb]
-パネルの各「辺」に、子要素をドッキングする領域を定義する。
--XAML
<DockPanel LastChildFill="True">
<Border Height="25" Background="SkyBlue" DockPanel.Doc...
<TextBlock Foreground="Black">Dock = "Top(1)"</Te...
</Border>
<Border Height="25" Background="SkyBlue" DockPanel.Doc...
<TextBlock Foreground="Black">Dock = "Top(2)"</Te...
</Border>
<Border Height="25" Background="LemonChiffon" DockPane...
<TextBlock Foreground="Black">Dock = "Bottom"</TextB...
</Border>
<Border Width="100" Background="PaleGreen" DockPanel.D...
<TextBlock Foreground="Black">Dock = "Left"</TextBlo...
</Border>
<Border Background="White">
<TextBlock Foreground="Black">
This content will "Fill" the remaining space
</TextBlock>
</Border>
</DockPanel>
--レンダリング結果
#ref(RenderingResultOfDockPanel.png,left,nowrap,ドック パ...
-DockPanel.LastChildFillプロパティ(LastChildFill属性)を...
DockPanelの最終の子要素は常に残りの領域を埋めるようになる。
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***スタック パネル [#i49c2e00]
-子要素を水平方向または垂直方向に整列する領域を定義する。
--XAML
---水平方向
<StackPanel Orientation="Horizontal">
<RadioButton Margin="4">test1</RadioButton>
<RadioButton Margin="4">test2</RadioButton>
<RadioButton Margin="4">test3</RadioButton>
</StackPanel>
---垂直方向
<StackPanel Orientation="Vertical">
<RadioButton Margin="4">test1</RadioButton>
<RadioButton Margin="4">test2</RadioButton>
<RadioButton Margin="4">test3</RadioButton>
</StackPanel>
--レンダリング結果
---水平方向
#ref(HorizontalRenderingResultOfStackPanel.png,left,nowra...
---垂直方向
#ref(VerticalRenderingResultOfStackPanel.png,left,nowrap,...
-整列方向は、StackPanel.Orientationプロパティ(Orientatio...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***折り返しパネル [#c1367ccd]
-子要素を水平方向または垂直方向に整列し、端に達したら改行...
※ パネルのサイズが変更されると、改行位置も変更される。
--XAML
---水平方向
<WrapPanel Orientation="Horizontal">
<Button Width="26" Height="26" Margin="4" Content="0">...
<Button Width="26" Height="26" Margin="4" Content="1">...
<Button Width="26" Height="26" Margin="4" Content="2">...
・・・
<Button Width="26" Height="26" Margin="4" Content="7">...
<Button Width="26" Height="26" Margin="4" Content="8">...
<Button Width="26" Height="26" Margin="4" Content="9">...
</WrapPanel>
---垂直方向
<WrapPanel Orientation="Vertical">
<Button Width="26" Height="26" Margin="4" Content="0">...
<Button Width="26" Height="26" Margin="4" Content="1">...
<Button Width="26" Height="26" Margin="4" Content="2">...
・・・
<Button Width="26" Height="26" Margin="4" Content="7">...
<Button Width="26" Height="26" Margin="4" Content="8">...
<Button Width="26" Height="26" Margin="4" Content="9">...
</WrapPanel>
--レンダリング結果
---水平方向
#ref(HorizontalRenderingResultOfWrapPanel.png,left,nowrap...
---垂直方向
#ref(VerticalRenderingResultOfWrapPanel.png,left,nowrap,...
-整列方向は、WrapPanel.Orientationプロパティ(Orientation...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***(均一)グリッド パネル [#h66a8f8e]
-列と行で構成されているグリッド領域を定義する。~
※ グリッド内のすべてのセルが同じサイズである必要がある。
--XAML
---3行 * 4列
<UniformGrid Rows="3" Columns="4">
<Button Width="26" Height="26" Margin="4" Content="0">...
<Button Width="26" Height="26" Margin="4" Content="1">...
<Button Width="26" Height="26" Margin="4" Content="2">...
・・・
<Button Width="26" Height="26" Margin="4" Content="7">...
<Button Width="26" Height="26" Margin="4" Content="8">...
<Button Width="26" Height="26" Margin="4" Content="9">...
</UniformGrid>
---4行 * 3列
<UniformGrid Rows="4" Columns="3">
<Button Width="26" Height="26" Margin="4" Content="0">...
<Button Width="26" Height="26" Margin="4" Content="1">...
<Button Width="26" Height="26" Margin="4" Content="2">...
・・・
<Button Width="26" Height="26" Margin="4" Content="7">...
<Button Width="26" Height="26" Margin="4" Content="8">...
<Button Width="26" Height="26" Margin="4" Content="9">...
</UniformGrid>
--レンダリング結果
---3行 * 4列
#ref(RenderingResultOfUniformGrid34.png,left,nowrap,3行 *...
---4行 * 3列
#ref(RenderingResultOfUniformGrid43.png,left,nowrap,4行 *...
-行・列数は、UniformGrid.Rows、UniformGrid.Columns属性(U...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***グリッド パネル [#p94f8aa7]
-列と行で構成されている柔軟なグリッド領域を定義する。
--行・列の定義にGrid.RowDefinitions、Grid.ColumnDefinitio...
---「添付プロパティ」であるGrid.Row・Grid.Column属性を使...
---列長・行長の設定も、この属性で指定する。
---このためHTMLのテーブルと使い方は異なる。
--XAML ( 4行 * 3列
<Grid Width="250" Height="100">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.ColumnSpan="3" Grid.Row="0">2005 Produ...
<TextBlock Grid.Row="1" Grid.Column="0">Quarter 1</Tex...
<TextBlock Grid.Row="1" Grid.Column="1">Quarter 2</Tex...
<TextBlock Grid.Row="1" Grid.Column="2">Quarter 3</Tex...
<TextBlock Grid.Row="2" Grid.Column="0">50000</TextBlo...
<TextBlock Grid.Row="2" Grid.Column="1">100000</TextBl...
<TextBlock Grid.Row="2" Grid.Column="2">150000</TextBl...
<TextBlock Grid.ColumnSpan="3" Grid.Row="3">Total Unit...
</Grid>
--レンダリング結果
#ref(RenderingResultOfGrid43.png,left,nowrap,4行 * 3列の...
-なお、ColumnDefinitionタグのWidth属性に" n*"と指定するこ...
--XAML ( 比率を指定
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"></RowDefinition>
<RowDefinition Height="2*"></RowDefinition>
<RowDefinition Height="3*"></RowDefinition>
</Grid.RowDefinitions>
</Grid>
--レンダリング結果
#ref(RenderingResultOfGridRatio.png,left,nowrap,比率指定...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
*スタイルとテンプレート [#j0c577be]
ココでは、「外観」に関する設定を行う「[[スタイル>#v30d5ab...
-参考
--MSDN > WPFの基礎 > スタイルとテンプレート : 概念~
http://msdn.microsoft.com/ja-jp/library/bb613570.aspx
---> スタイルとテンプレート~
http://msdn.microsoft.com/ja-jp/library/ms745683.aspx
---> ControlTemplateの作成による既存のコントロールの外観...
http://msdn.microsoft.com/ja-jp/library/ee230084.aspx
--MSDN > Windows Presentation Foundation > コントロール
---> コントロールのカスタマイズ > ControlTemplateの例~
http://msdn.microsoft.com/ja-jp/library/aa970773.aspx
**スタイル [#v30d5ab6]
[[WPF]] / [[Silverlight]]で外観をカスタマイズする仕組みの...
***スタイルの基本 [#x9dade50]
「スタイル」は、UI要素の「依存関係プロパティ」の一括管理...
「スタイル」は、Style型のオブジェクトであり、各UI要素(Fr...
-外観に関する値を設定する「[[プロパティ属性構文>#tb0bd2e6...
以下は、UI要素の「依存関係プロパティ」に、「外観」に関す...
--XAML
<Grid>
<Ellipse Fill="Blue" Height="80" Width="160"/>
</Grid>
--レンダリング結果
#ref(RenderingResultOfStyle1.png,left,nowrap,外観に関する...
-[[プロパティ属性構文>#tb0bd2e6]]のスタイル化
--上記を、「[[プロパティ要素構文>#s389a559]]」を使用してS...
---TargetType属性により、「スタイル」は指定の型(ここでは...
---このTargetType属性による型指定が無いと、対象のプロパテ...
--XAML
<Grid>
<Ellipse>
<Ellipse.Style>
<Style TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</Ellipse.Style>
</Ellipse>
</Grid>
--レンダリング結果
#ref(RenderingResultOfStyle2.png,left,nowrap,プロパティ属...
-スタイルを[[リソース>#p50dd8ac]]として定義
--なお、上記の「スタイル」化は、通常のプロパティ設定を冗...
--このため、通常、「スタイル」を「[[リソース>#p50dd8ac]]...
--以下は、x:Keyを明示した例である。
---XAML
<StackPanel.Resources>
<Style x:Key="EllipseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</StackPanel.Resources>
<Ellipse Style="{StaticResource EllipseStyle}"/>
<Ellipse Style="{StaticResource EllipseStyle}"/>
</StackPanel>
---レンダリング結果
#ref(RenderingResultOfStyle3.png,left,nowrap,スタイルをリ...
-ベースクラスの型にスタイルを適用~
また、派生元(ここではShape型)が同じであれば、異なる要素...
--XAML
<StackPanel>
<StackPanel.Resources>
<Style x:Key="ShapeStyle" TargetType="Shape">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</StackPanel.Resources>
<Ellipse Style="{StaticResource ShapeStyle}"/>
<Rectangle Style="{StaticResource ShapeStyle}"/>
</StackPanel>
--レンダリング結果
#ref(RenderingResultOfStyle4.png,left,nowrap,ベースクラス...
-スタイルを全体に適用する例~
x:Keyを設定しなければ、TargetType属性により、「スタイル」...
(ただし、派生元が同じだが、型の異なる全ての要素に「スタ...
--XAML
<StackPanel>
<StackPanel.Resources>
<Style TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</StackPanel.Resources>
<Ellipse/>
<Ellipse/>
</StackPanel>
--レンダリング結果
#ref(RenderingResultOfStyle5.png,left,nowrap,スタイルを全...
***スタイルの継承 [#g2818cb4]
-TargetType プロパティが同じ2つのStyleクラスを定義し、~
BasedOnプロパティに継承元となるStyleクラスを設定すること...
>「スタイル」の継承が可能である。
>(Silverlight 2のStyleクラスにはBasedOnプロパティが存在...
-スタイルの継承例
--XAML
<StackPanel>
<StackPanel.Resources>
<Style x:Key="EllipseBaseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
<Style x:Key="EllipseInheritedStyle" TargetType="Ell...
BasedOn="{StaticResource EllipseBaseStyle}">
<Setter Property="Stroke" Value="Yellow"/>
<Setter Property="StrokeThickness" Value="10"/>
</Style>
</StackPanel.Resources>
<Ellipse Style="{StaticResource EllipseBaseStyle}"/>
<Ellipse Style="{StaticResource EllipseInheritedStyle}...
</StackPanel>
--レンダリング結果
#ref(RenderingResultOfInheritedStyle.png,left,nowrap,スタ...
***外部ディクショナリ ファイル化 [#je240854]
-「ディクショナリ ファイル」を使用して、CSSファイルのよう...
「スタイル」を外部ディクショナリ ファイルに定義することも...
-以下は、「ディクショナリ ファイル」を使用する例である。
--XAML
<Window.Resources>
<ResourceDictionary Source="Dictionary1.xaml"/>
</Window.Resources>
<StackPanel>
<StackPanel.Resources>
<Style x:Key="EllipseInheritedStyle" TargetType="Ell...
BasedOn="{StaticResource EllipseBaseStyle}">
<Setter Property="Stroke" Value="Yellow"/>
<Setter Property="StrokeThickness" Value="10"/>
</Style>
</StackPanel.Resources>
<Ellipse Style="{StaticResource EllipseBaseStyle}"/>
<Ellipse Style="{StaticResource EllipseInheritedStyle}...
</StackPanel>
--XAML ( 外部ディクショナリ ファイル : Dictionary1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="EllipseBaseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</ResourceDictionary>
***実行時スタイル [#aef5f69e]
-「[[リソースの定義と参照>#wd960230]]」の
--DynamicResource参照
--ディクショナリ ファイル
>の方法を、「スタイル」でも応用可能である。
-上記の例のXAMLを以下のように書き換え、~
コード ビハインドからResourceDictionaryを切り換え~
「スタイル」(スキン)を実行時に、動的に切り換えることが...
--XAML
<StackPanel>
<Ellipse Style="{DynamicResource MyEllipseStyle}"/>
<Button Content="青" Height="23" Name="button1" Width=...
<Button Content="赤" Height="23" Name="button2" Width=...
</StackPanel>
--XAML ( 外部ディクショナリ ファイル :
---Dictionary1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="MyEllipseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</ResourceDictionary>
---Dictionary2.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xam...
<Style x:Key="MyEllipseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Red"/>
<Setter Property="Height" Value="160"/>
<Setter Property="Width" Value="80"/>
</Style>
</ResourceDictionary>
--コード・ビハインド
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
this.LoadResourceDictionary("Dictionary1.xaml");
}
private void button1_Click(object sender, RoutedEventA...
this.LoadResourceDictionary("Dictionary1.xaml");
}
private void button2_Click(object sender, RoutedEventA...
this.LoadResourceDictionary("Dictionary2.xaml");
}
private void LoadResourceDictionary(string name) {
ResourceDictionary dictionary =
(ResourceDictionary)Application.LoadComponent(new ...
if (dictionary != null) Application.Current.Resource...
}
}
--レンダリング結果
#ref(RenderingResultOfStyleAtRuntime.png,left,nowrap,実行...
**テンプレート [#o64ea160]
[[WPF]] / [[Silverlight]]で外観をカスタマイズする仕組みの...
***テンプレートの基本 [#l20b9ab9]
-「[[コンテンツ構文>#m4c088a5]]」でも述べたように、WPFのU...
「[[プロパティ属性構文>#tb0bd2e6]]」と「[[プロパティ要素...
--「[[スタイル>#v30d5ab6]]」属性の設定だけでなく、
--[[Contentプロパティ>#gc84bde8]](または[[Itemsプロパテ...
>このため、WPFのUIコントロールはコントロールの「外観」を...
|#|コントロールのクラス型|コンテンツを設定するプロパティ|...
|1|ContentControlクラス|[[Contentプロパティ>#gc84bde8]]|C...
|2|ItemsControlクラス|[[Itemsプロパティ>#v7960713]]|Items...
-また、「テンプレート」により、
--コントロールの「外観」を宣言型マークアップでカスタマイ...
--また、「イベント ハンドラ」や「イベント トリガ」なども...
「テンプレート」を「[[スタイル>#v30d5ab6]]」化、「[[リソ...
-「テンプレート」は、コントロールの用途毎に、複数のものが...
--テンプレートを設定するのプロパティと、テンプレートの型
|#|>|テンプレートを設定するプロパティ|テンプレートのクラ...
|1|>|[[Control.Template>http://msdn.microsoft.com/ja-jp/l...
|1-1||ContentControlの(Control. )Templateプロパティ|~||...
|1-2||ItemsControlの(Control. )Templateプロパティ|~||It...
|2|>|XXXX.XXXXTemplate|[[DataTemplate>http://msdn.microso...
|2-1||[[ContentControl.ContentTemplate>http://msdn.micros...
|2-2||[[ItemsControl.ItemTemplate>http://msdn.microsoft.c...
|3|>|その他|-|>|種々のコントロールの個別領域の外観をカス...
|3-1||[[ItemsControl.ItemsPanel>https://msdn.microsoft.co...
|3-2||[[HeaderedContentControl.HeaderTemplate>https://msd...
|3-3||[[GridViewColumn.CellTemplate>https://msdn.microsof...
-ただし、「テンプレート」で作成できる「外観」は、静的なも...
***ControlTemplateとDataTemplate [#n86551dd]
-ControlTemplate
--Control自身の見た目を決定するもの。
--多くの場合TemplateBindingを使い、テンプレート親とのコン...
-DataTemplate
--Controlに割り当てられたデータの見た目を定義するもの。
--多くの場合Bindingを使い、割り当てられたデータとのバイン...
-ControlTemplateとDataTemplateの使い分け
--その1
---ControlTemplate~
カスタマイズしたいものがコントロール自身である場合にを利...
---DataTemplate~
カスタマイズしたいものが割り当てられるデータである場合に...
--その2~
状況によっては、ControlTemplate、DataTemplateの~
どちらを使っても可能なこともあるので、再利用性で考える。
---ControlTemplate~
そのカスタマイズした結果できるであろうコントロールに、別...
---DataTemplate~
そのカスタマイズした結果できるであろうコントロールに、別...
--その3
---ControlTemplate~
ContentControlをカスタマイズする場合。
---DataTemplate~
ItemsControlをカスタマイズする場合。
***「テンプレート」値を反映させる方法 [#wc88b865]
また、親コントロールに適用した、「テンプレート」の値を~
[[Contentプロパティ>#gc84bde8]](または[[Itemsプロパティ>...
プロパティ値に反映させるにめには、下記の3通りの方法を選択...
-「プレゼンター」を利用する方法
--親コントロールの[[Contentプロパティ>#gc84bde8]]の場合は...
[[Contentプロパティ>#gc84bde8]]は、任意の型の子要素を取得...
--また、ItemsControlの[[Itemsプロパティ>#v7960713]]に対応...
[[Itemsプロパティ>#v7960713]]は、任意の型の子要素を取得し...
--その他、コントロールによって、色々なテンプレート・プレ...
---テンプレート : ItemsControl.ItemsPanelプロパティのItem...
>参考 : FrameworkTemplate クラス (System.Windows)~
https://msdn.microsoft.com/ja-jp/library/system.windows.f...
---プレゼンター : ScrollContentPresenter, CellValuePresen...
>参考 : 【WPF】Presenter(?)クラスを収集と考察。 | 創造...
http://pro.art55.jp/?eid=931821
-[[TemplateBinding の「マークアップ拡張」>#hee73def]]を使...
親コントロールに適用したプロパティ値を「テンプレート」に...
<object property="{TemplateBinding TargetProperty }" .../>
-同様に、[[RelativeSource の「マークアップ拡張」>#b35e6e7...
<Binding RelativeSource="{RelativeSource TemplatedParent...
--なお、「データ バインディング」で使用する場合は、次のよ...
<object property="{Binding RelativeSource={RelativeSourc...
--RelativeSourceの例
---XAML
<StackPanel>
<TextBlock Text="{Binding RelativeSource
={RelativeSource Self}, Path=FontFamily}" />・・・(1)
<Border Background="Black" Height="5"/>
<TextBlock Text="{Binding RelativeSource
={RelativeSource AncestorType={x:Type StackPanel}},P...
<Border Background="Black" Height="5"/>
<Button Content="Hello world">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<ContentPresenter Content="{Binding RelativeSource
={RelativeSource TemplatedParent}, Path=Conten...
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
---レンダリング結果
#ref(RenderingResultOfRelativeSource.png,left,nowrap,Rela...
--説明
---(1) では、TextBlock要素自身のFontFamilyプロパティを取...
---(2) では、親要素(AncestorType 属性に指定されているSta...
---(3) では、TemplatedParent 属性により、[[テンプレート>#...
[[Contentプロパティ>#gc84bde8]]を取得し、ContentPresenter...
***参考 [#s29b90e0]
-MSDN > Windows Presentation Foundation
--> データ > データ バインディング > データ テンプレート...
http://msdn.microsoft.com/ja-jp/library/ms742521.aspx
-WPF4.5入門 - かずきのBlog@hatena
--その47 「コンテンツモデル」~
http://blog.okazuki.jp/entry/2014/08/25/164331
--その52 「コントロールテンプレート」~
http://blog.okazuki.jp/entry/2014/09/07/195335
-WPFコントロールテンプレートとデータテンプレートの違い | ...
https://tocsworld.wordpress.com/2014/09/28/wpf%E3%82%B3%E...
**テンプレートの例 [#f9a8fb1a]
***ContentControlのテンプレート(ControlTemplate)の例 [#...
-XAML
--以下は、ControlTemplateとContentPresenterを使用したCont...
<Grid>
<Button Margin="5" Width="100" Height="100" Content="...
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
--上記のContentPresenterを、「マークアップ拡張」のTemplat...
<Grid>
<Button Margin="5" Width="100" Height="100" Content="...
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<TextBlock
Text="{TemplateBinding Content}"
HorizontalAlignment="Center" VerticalAlignme...
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
--上記のTemplateBindingを、「マークアップ拡張」のRelative...
なお、RelativeSourceの場合、TargetType属性を消しても上手...
<Grid>
<Button Margin="5" Width="100" Height="100" Content="...
<Button.Template>
<ControlTemplate>
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<TextBlock
Text="{Binding Path=Content, RelativeSource=...
HorizontalAlignment="Center" VerticalAlignme...
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
-レンダリング結果
#ref(RenderingResultOfControlTemplate.png,left,nowrap,Con...
-スタイル化
--「テンプレート」は、以下のように「スタイル」に組み込む...
---XAML
<Window.Resources>
<Style x:Key="buttonTemplate" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Margin="5" Width="100" Height="100">ボタン1</...
<Button Margin="5" Width="100" Height="100">ボタン2</...
<Button Margin="5" Width="100" Height="100"
Style="{StaticResource buttonTemplate}">ボタン3</Bu...
</StackPanel>
---レンダリング結果
#ref(RenderingResultOfStyleTemplate1.png,left,nowrap,Cont...
--なお、x:Keyを設定しなければ、TargetType属性により、~
「スタイル」は指定の型(ここではButtonコントロール)、全...
---XAML
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Margin="5" Width="100" Height="100">ボタン1</...
<Button Margin="5" Width="100" Height="100">ボタン2</...
<Button Margin="5" Width="100" Height="100">ボタン3</...
</StackPanel>
---レンダリング結果
#ref(RenderingResultOfStyleTemplate2.png,left,nowrap,Cont...
-リソース化
--「テンプレート」と「スタイル」を別々の「リソース」とし...
StaticResource参照の「マークアップ拡張」により~
「テンプレート」を「スタイル」に組み込むことも可能である。
---XAML
<Window.Resources>
<ControlTemplate x:Key="buttonTemplate" TargetType="Bu...
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
<Style TargetType="Button">
<Setter Property="Template" Value="{StaticResource b...
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Margin="5" Width="100" Height="100">ボタン1</...
<Button Margin="5" Width="100" Height="100">ボタン2</...
<Button Margin="5" Width="100" Height="100">ボタン3</...
</StackPanel>
--以下、同様に、「ディクショナリ ファイル」を使用して、CS...
「テンプレート」を外部ファイルに定義することも可能である。
---XAML
<Window.Resources>
<ResourceDictionary Source="TemplateStyleDictionary.xa...
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Margin="5" Width="100" Height="100">ボタン1</...
<Button Margin="5" Width="100" Height="100">ボタン2</...
<Button Margin="5" Width="100" Height="100">ボタン3</...
</StackPanel>
---XAML ( 外部ディクショナリ ファイル : TemplateStyleDict...
<ResourceDictionary xmlns="http://schemas.microsoft.com/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ControlTemplate x:Key="buttonTemplate" TargetType="Bu...
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
<Style TargetType="Button">
<Setter Property="Template" Value="{StaticResource b...
</Style>
</ResourceDictionary>
--レンダリング結果
#ref(RenderingResultOfStyleTemplate2.png,left,nowrap,Cont...
***ContentControlのテンプレート(DataTemplate)の例 [#i42...
-以下は、ControlTemplate + ContentPresenterとDataTemplat...
--XAML
<Grid>
<Button Content="Click Here"
Margin="5" Width="100" Height="100">
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
<Button.ContentTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding}"/>
</Grid>
</DataTemplate>
</Button.ContentTemplate>
</Button>
</Grid>
--レンダリング結果
#ref(RenderingResultOfDataTemplateOfContentControl.png,le...
--上記の通り、DataTemplate内でContentプロパティのデータを...
-DataTemplateのポイント
--通常、ContentControl内にはContentControl.Contentプロパ...
ControlTemplateだけで事足りることが多く、DataTemplateの利...
--なお、ControlTemplate + ContentPresenterとDataTemplate...
必ずしも併用しなくても良い(DataTemplateのみの利用も可能...
--DataTemplate内でContentプロパティ以外のデータを使用する...
<TextBlock Text="{Binding RelativeSource={RelativeSource...
>>などの記述方法がある。
***ItemsControlのテンプレート(DataTemplate)の例 [#p680d...
-以下は、ItemsControl.ItemTemplateプロパティを使用したLis...
--これは、前述のサンプルの改良版である。
---[[Itemsプロパティ>#v7960713]]
---[[データ バインディングの基礎>#h0ae3316]]
--基本的に、~
ItemsControlコントロールに「データ バインディング」を行っ...
ItemsControl.ItemTemplateプロパティへ、DataTemplateを指定...
--コード
---XAML
<Grid>
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="ListBox1" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush ="Black" BorderThickness =...
<StackPanel Orientation="Horizontal" Height=...
<Image Height="100" Source="{Binding Path=...
<TextBlock Text="{Binding Path=[Text]}" V...
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
---コード ビハインド
public Window1() {
InitializeComponent();
List<Dictionary<string, string>> lst
= new List<Dictionary<string, string>>();
Dictionary<string, string> dic = null;
dic = new Dictionary<string, string>();
dic["Image"] = @".\Blue hills.jpg";
dic["Text"] = "Blue hills";
lst.Add(dic);
dic = new Dictionary<string, string>();
dic["Image"] = @".\Sunset.jpg";
dic["Text"] = "Sunset";
lst.Add(dic);
dic = new Dictionary<string, string>();
dic["Image"] = @".\Water lilies.jpg";
dic["Text"] = "Water lilies";
lst.Add(dic);
dic = new Dictionary<string, string>();
dic["Image"] = @".\Winter.jpg";
dic["Text"] = "Winter";
lst.Add(dic);
this.stackPanel1.DataContext = lst;
}
---補足~
補足となるが、選択したオブジェクトは、以下のコードで取得...
Dictionary<string, string> dic = (Dictionary<string, str...
-なお、「バインディング ソース」にDataTableを使用する場合...
--DataTableのDataColumnのColumnNameプロパティをPath属性に...
「通常のプロパティの場合の記述方法」・「インデクサの場合...
--また、ここでは、「テンプレート」を「リソース」として定...
--コード
---XAML
<Window.Resources>
<DataTemplate x:Key="listBoxStyle">
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Height="100" Source="{Binding Path=Image}...
<TextBlock Text="{Binding Path=[Text]}" Vertica...
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="ListBox1"
ItemsSource="{Binding}" ItemTemplate="{StaticResou...
</StackPanel>
</Grid>
---コード ビハインド
public Window1() {
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Image"));
dt.Columns.Add(new DataColumn("Text"));
DataRow dr = null;
dr = dt.NewRow();
dr["Image"] = @".\Blue hills.jpg";
dr["Text"] = "Blue hills";
dt.Rows.Add(dr);
・・・
dr = dt.NewRow();
dr["Image"] = @".\Winter.jpg";
dr["Text"] = "Winter";
dt.Rows.Add(dr);
this.stackPanel1.DataContext = dt;
}
---補足~
補足となるが、選択したオブジェクトは、以下のコードで取得...
DataRow dr = (DataRow)this.ListBox1.SelectedValue;
-レンダリング結果
#ref(RenderingResultOfDataTemplateOfItemsControl.png,left...
***ItemsControl(DisplayMemberPath, SelectedValuePath)の...
-ここまで、ItemsControl.ItemTemplateプロパティへ、DataTem...
代表的なItemsControlコントロールであるListBoxやComboBox(...
DisplayMemberPath、SelectedValuePathなどの属性を持ってい...
-このため、単純な表示であればItemsControl.ItemTemplateプ...
「データ バインディング」したオブジェクトから「表示項目」...
-以下、その例を示す。
--XAML
<Grid>
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="ListBox1" ItemsSource="{Binding}"
SelectedValuePath="Value" DisplayMemberPath="Displ...
<Button Click="Button_Click">選択値</Button>
</StackPanel>
</Grid>
--コード ビハインド
public Window1() {
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Value"));
dt.Columns.Add(new DataColumn("Display"));
DataRow dr = null;
dr = dt.NewRow();
dr["Value"] = "0001";
dr["Display"] = "0001の表示";
dt.Rows.Add(dr);
・・・
dr = dt.NewRow();
dr["Value"] = "0004";
dr["Display"] = "0004の表示";
dt.Rows.Add(dr);
this.stackPanel1.DataContext = dt;
}
--レンダリング結果
#ref(RenderingResultOfListBox1.png,left,nowrap,SelectedVa...
-DisplayMemberPath属性に指定されたデータが表示項目となり、~
SelectedValuePath属性に指定されたデータがSelectedValueプ...
以下は、選択されたデータを取得するコードの例である。
--コード ビハインド
private void Button_Click(object sender, RoutedEventArgs...
MessageBox.Show(this.ListBox1.SelectedValue.ToString());
}
--選択されたデータ
#ref(RenderingResultOfListBox2.png,left,nowrap,SelectedVa...
***その他のItemsControlのテンプレートの例 [#eb36bade]
-ControlTemplateを使用したItemsControl
--以下は、ControlTemplateを使用したItemsControl(ListBox...
--通常、ItemsControlではDataTemplateだけで事足りることが...
ここではControlTemplate内でItemsPresenterを使用してItems...
--XAML
<Grid>
<ListBox>
<ListBox.Template>
<ControlTemplate>
<ItemsPresenter Margin="5" HorizontalAlignment="...
</ControlTemplate>
</ListBox.Template>
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
</ListBox>
</Grid>
--レンダリング結果
#ref(RenderingResultOfControlTemplateOfItemsControl.png,l...
-ItemsPanelTemplateを使用したItemsControl
--Itemsプロパティのデータの並び(レイアウト)は、~
ItemsControl.ItemsPanel プロパティにItemsPanelTemplate を...
--ここではStackPanelを使用し、各アイテムの並びを横並びに...
--XAML
<Grid>
<ListBox>
<ListBox.Template>
<ControlTemplate TargetType="ListBox">
<ItemsPresenter Margin="5" HorizontalAlignment="...
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
</ListBox>
</Grid>
--レンダリング結果
#ref(RenderingResultOfItemsPanelTemplate.png,left,nowrap,...
--参考
---MSDN > .NET Frameworkクラス ライブラリ~
● System.Windows.Controls.ItemsControl.ItemsPanelプロパテ...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
● System.Windows.Controls.ItemsPanelTemplateクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
-ヘッダの追加(ControlTemplate)
--ItemsControlでは、ControlTemplateは(繰り返し項目以外の...
--以下、ヘッダをControlTemplateで実装し、データをDataTemp...
--コード
---XAML
<Grid>
<ListBox Name="listBox1" ItemsSource="{Binding}">
<ListBox.Template>
<ControlTemplate>
<StackPanel>
<StackPanel Orientation="Horizontal" Backgrou...
<TextBlock Width="100" Text="ヘッダ1"/>
<TextBlock Width="100" Text="ヘッダ2"/>
</StackPanel>
<ItemsPresenter/> ・・・ItemsPresenterを忘れな...
</StackPanel>
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Width="100" Text="{Binding Path=[da...
<TextBlock Width="100" Text="{Binding Path=[da...
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
---コード ビハインド
public Window1() {
InitializeComponent();
List<Dictionary<string, string>> lst = new List<Dictio...
Dictionary<string, string> dic = null;
dic = new Dictionary<string, string>();
dic["data1"] = "データ11";
dic["data2"] = "データ11";
lst.Add(dic);
dic = new Dictionary<string, string>();
dic["data1"] = "データ21";
dic["data2"] = "データ22";
lst.Add(dic);
this.listBox1.DataContext = lst;
}
--レンダリング結果
#ref(RenderingResultOfControlTemplateOfItemsControlWithHe...
--グリッド系のコントロールには、ヘッダ専用の「テンプレー...
-各種テンプレートの組み合わせ~
以下は、DataTemplate、ControlTemplate、ItemsPanelTemplate...
[[ItemsControlのテンプレート(DataTemplate)の例>#p680d34...
ItemsControl(ListBox)コントロールの例である(中央揃え+...
--コード
---XAML
<Grid>
<StackPanel x:Name="stackPanel1">
<Button x:Name="button1" Click="button1_Click">選択<...
<ListBox x:Name="ListBox1" ItemsSource="{Binding}">
<ListBox.Template>
<ControlTemplate>
<ItemsPresenter Margin="5" HorizontalAlignment...
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush ="Black" BorderThickness =...
<StackPanel Orientation="Horizontal" Height=...
<Image Height="100" Source="{Binding Path=...
<TextBlock Text="{Binding Path=[Text]}" V...
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
---コード ビハインド
public Window1() {
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Image"));
dt.Columns.Add(new DataColumn("Text"));
DataRow dr = null;
dr = dt.NewRow();
dr["Image"] = @".\Blue hills.jpg";
dr["Text"] = "Blue hills";
dt.Rows.Add(dr);
・・・
dr = dt.NewRow();
dr["Image"] = @".\Winter.jpg";
dr["Text"] = "Winter";
dt.Rows.Add(dr);
this.stackPanel1.DataContext = dt;
}
private void Button_Click(object sender, RoutedEventArgs...
MessageBox.Show(this.ListBox1.SelectedValue.ToString());
}
--レンダリング結果
#ref(RenderingResultOfVariousTemplatesOfItemsControl.png,...
***グリッド系コントロールの例 [#dcea1bb1]
-ヘッダ・セルのカスタマイズ~
以下、ListViewコントロールのヘッダとセルのカスタマイズの...
--コード
---XAML
<Window.Resources>
<Style x:Key="listViewItemStyle" TargetType="ListViewI...
<Setter Property="BorderBrush" Value="Gray"/>
<Setter Property="BorderThickness" Value="2"/>
</Style>
<DataTemplate x:Key="listViewHeaderTemplate">
<TextBlock FontSize="16" Foreground="Navy" Text="{Bi...
</DataTemplate>
<DataTemplate x:Key="listViewCellStyle">
<Border BorderBrush ="Black" BorderThickness ="5" Ma...
<Image Height="100" Source="{Binding Path=Image}" />
</Border>
</DataTemplate>
</Window.Resources>
<StackPanel x:Name="stackPanel1">
<ListView x:Name="listView1" ItemsSource="{Binding}"
ItemContainerStyle="{StaticResource listViewItemStyl...
<ListView.View>
<GridView ColumnHeaderTemplate="{StaticResource li...
<GridViewColumn Header="名称"
DisplayMemberBinding="{Binding Path=Text}" />
<GridViewColumn Header="画像"
CellTemplate="{StaticResource listViewCellStyl...
</GridView>
</ListView.View>
</ListView>
</StackPanel>
---コード ビハインド
public Window1() {
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Image"));
dt.Columns.Add(new DataColumn("Text"));
DataRow dr = null;
dr = dt.NewRow();
dr["Image"] = @".\Blue hills.jpg";
dr["Text"] = "Blue hills";
dt.Rows.Add(dr);
・・・
this.stackPanel1.DataContext = dt;
}
--レンダリング結果
#ref(RenderingResultOfGridControlWithHeader.png,left,nowr...
--グリッド系のコントロール(ListView・GridView)は、以下...
---GridViewColumn クラスを使用した列の定義、
---GridViewColumn.CellTemplate プロパティへの列「テンプレ...
---GridView.ColumnHeaderTemplate プロパティへのヘッダ「テ...
-セルにComboBoxを入れる
--ListViewコントロールのセルにComboBoxを入れることも可能...
この場合、列「テンプレート」を定義して、GridViewColumn.Ce...
--この際、「データ バインディング」を使用してComboBoxを初...
StaticResourceを使用した「データ バインディング」にて行う...
このため、ComboBoxボックス毎に「リソース」に定義するクラ...
--この処理を実装する際のポイントは、以下のとおりである。
---ComboBoxボックス毎に「リソース」に定義するクラス型を作...
基本クラスなどを用いて、このクラス型の定義を簡単に行える...
---上記で作成したComboBoxボックス毎に「リソース」に定義す...
各クラスのコンストラクタに実装する必要があるが、3層C/S型...
ラウンドトリップが多くなってしまうことがあるため、集約し...
--サンプル~
https://github.com/OpenTouryoProject/SampleProgram/tree/m...
*トリガ [#x73e9a3a]
-トリガは、
--Style 、ControlTemplate 、DataTemplate などの、~
UIElementの視覚化を指定するオブジェクトのプロパティとして...
--「ある事象」をきっかけにして、そのUIElementの視覚設定を...
>ものである。
-トリガには、以下の3種類が存在し、それぞれ、きっかけとな...
--プロパティ トリガ~
きっかけ:上記の適用されているUIElementのプロパティの変更
--データ トリガ~
きっかけ:UIElementにバインドされたデータのプロパティの変更
--イベント トリガ~
きっかけ:上記の適用されているUIElementでハンドルできる「...
-以下、それぞれのトリガについて説明する。
**プロパティ トリガ [#z60358ba]
-プロパティ トリガは、UIElementのプロパティ値に基づく。
-データトリガには、Triggerと、MultiTriggerの2つがある。
-以下は、プロパティ トリガとStyleを組み合わせて利用した例...
--XAML
<Window.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button...
<Setter Property="Background" Value="LightYellow" />
<!--IsPressed = True で、背景色変更-->
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="LightBlue" />
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="ButtonStyle2" TargetType="{x:Type Button...
<Setter Property="Background" Value="LightYellow" />
<!--IsMouseOver = True で、背景色変更-->
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="LightBlue" />
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="ButtonStyle3" TargetType="{x:Type Button...
<Setter Property="Background" Value="LightYellow" />
<!--IsMouseOver、IsFocused = True で、背景色変更-->
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
<Condition Property="IsFocused" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="Background" Value="LightBlue" />
</MultiTrigger >
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Style="{StaticResource ButtonStyle1}" Grid.Row...
<Button Style="{StaticResource ButtonStyle2}" Grid.Row...
<Button Style="{StaticResource ButtonStyle3}" Grid.Row...
</Grid>
--レンダリング結果
#ref(RenderingResultOfPropertyTrigger.png,left,nowrap,プ...
-参考
--MSDN > .NET Frameworkクラス ライブラリ
---> System.Windows.Triggerクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.tr...
---> System.Windows.MultiTriggerクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.mu...
**データ トリガ [#af3def31]
-データ トリガは、UIElementのプロパティ値ではなく、~
バインドされたデータのプロパティ値に基づく。
-データトリガには、DataTriggerと、MultiDataTriggerの2つが...
-以下は、データ トリガとStyleを組み合わせて利用した例であ...
--コード
---XAML
<Window.Resources>
<my:Places x:Key="PlacesData"/>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<!--DataTrigger(Condition×1)-->
<!-- State = WA の行は文字色 = 赤-->
<DataTrigger Binding="{Binding Path=State}" Value=...
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
<!--MultiDataTrigger(Condition×n)-->
<!-- Name = Portland, State = OR の行は背景色 = 黄...
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Name}" Value...
<Condition Binding="{Binding Path=State}" Valu...
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Yellow" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
<DataTemplate DataType="{x:Type my:Place}">
<StackPanel Orientation="Horizontal" HorizontalAlign...
<TextBlock Width="20"/>
<TextBlock Width="100" Text="{Binding Path=Name}"/>
<TextBlock Width="20"/>
<TextBlock Text="{Binding Path=State}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<TextBlock Margin="5" HorizontalAlignment="Center">Dat...
<ListBox HorizontalAlignment="Stretch"
ItemsSource="{Binding Source={StaticResource ...
</StackPanel>
---コード ビハインド~
カスタムクラスであるPlaces(前述のXAMLのWindow.Resources...
(StaticResourceから)直接初期化できるように以下のように...
/// <summary>Place</summary>
public class Place {
/// <summary>名前</summary>
private string _name;
/// <summary>状態</summary>
private string _state;
/// <summary>名前</summary>
public string Name {
get { return _name; }
set { _name = value; }
}
/// <summary>状態</summary>
public string State {
get { return _state; }
set { _state = value; }
}
/// <summary>コンストラクタ</summary>
public Place(string name, string state) {
this._name = name;
this._state = state;
}
}
public class Places : ObservableCollection<Place> {
/// <summary>コンストラクタで</summary>
public Places() {
this.Add(new Place("Bellevue", "WA"));
this.Add(new Place("Gold Beach", "OR"));
this.Add(new Place("Kirkland", "WA"));
this.Add(new Place("Los Angeles", "CA"));
this.Add(new Place("Portland", "ME"));
this.Add(new Place("Portland", "OR"));
this.Add(new Place("Redmond", "WA"));
this.Add(new Place("San Diego", "CA"));
this.Add(new Place("San Francisco", "CA"));
this.Add(new Place("San Jose", "CA"));
this.Add(new Place("Seattle", "WA"));
}
}
--レンダリング結果
#ref(RenderingResultOfDataTrigger.png,left,nowrap,データ ...
-参考
--MSDN > .NET Frameworkクラス ライブラリ
---> System.Windows.DataTriggerクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.da...
---> System.Windows.MultiDataTriggerクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.mu...
**イベント トリガ [#p908262c]
-通常、イベント トリガはアニメーション処理開始の指定のた...
-これについては、「[[アニメーション>XAMLの書き方(2)#x6...
-なお、イベント トリガはFrameworkElementにも指定すること...
-参考
--MSDN > .NET Frameworkクラス ライブラリ
---> System.Windows.FrameworkElement.Triggersプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.fr...
----
Tags: [[:.NET開発]], [[:UIサブシステム]], [[:WPF/Silverli...
終了行:
「[[マイクロソフト系技術情報 Wiki>http://techinfoofmicros...
-[[戻る>XAML]]
--XAMLの書き方(1)
--[[XAMLの書き方(2)]]
* 目次 [#i78ae0d5]
#contents
*概要 [#d37660b8]
基本的なXAMLの書き方。
*名前空間 [#x46c4d22]
XAMLにおける各種の名前空間の宣言は、xmlns属性を使用したXM...
ここでは、以下の既定の名前空間の宣言を例にとって説明する。
-名前空間の宣言
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
-XML名前空間の簡単な説明~
http://www.kanzaki.com/docs/sw/names.html
**WPF名前空間 [#u9e59dba]
2行目のXML名前空間の宣言(xmlns="http://schemas.microsoft...
WPFフレームワーク(PresentationFramework.dll)のアセンブ...
CLR名前空間(System.Windows.Controls、System.Windows.Data...
そのため、既定でXAMLからWPFフレームワークのCLRオブジェク...
**XAML名前空間 [#f7e47ba4]
3行目のXML名前空間の宣言(xmlns:x="http://schemas.microso...
URIにマップされた共通的なXAMLの言語機能がXML名前空間(x)...
これにより、「x:」というプレフィックスを使用することで、...
**CLR名前空間 [#b9a3d659]
CLR名前空間について以下を例にとって説明する。
***(1) [#j611ebcc]
-CLR名前空間の宣言
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
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....
http://msdn.microsoft.com/ja-jp/library/system.windows.ma...
なお、XML名前空間には一意の名前を自由に付与でき(上記の例...
このプレフィックスを使用することで、XAMLからUIコンポーネ...
***(2) [#y81abbb2]
この他に、URIとしてCLR名前空間とアセンブリを直接指定する...
-CLR名前空間の宣言
xmlns:sys="clr-namespace:(CLR名前空間);assembly=(アセ...
--例1:サードパーティ製品
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:igDP="clr-namespace:Infragistics.Windows.DataPre...
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/pr...
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/pr...
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名前空間を指定する場合は、「asse...
--XML名前空間には一意の名前を自由に付与でき、このプレフィ...
-製品並みのカスタムのUIコントロールを開発・使用するなどの...
--一般的には「clr-namespace、assembly」の定義済みトークン...
--ただし、この方法は、1つのCLR名前空間に対して、1つのXM...
--(XmlnsDefinitionアセンブリ属性を使用すると、1つのXML...
***参考 [#v51c1b09]
-MSDN > WPFの基礎 > WPFのXAML > XAML名前空間およびWPF XAM...
http://msdn.microsoft.com/ja-jp/library/ms747086.aspx
*言語機能 [#ad009a58]
XAMLの言語機能である
-「[[ディレクティブ>#j78f478c]]」
-「[[マークアップ拡張>#b565ab69]]」
について説明する。
-MSDN > .NET Framework XAMLサービスの概念説明のドキュメン...
http://msdn.microsoft.com/ja-jp/library/ms753327.aspx
**ディレクティブ [#j78f478c]
XAMLの言語機能が提供する各種ディレクティブについて説明す...
|項番|ディレクティブ|説明|h
|~|~|例|h
|1|x:Class|XAML上から分離クラス(コード ビハインド)のク...
|~|~|<Window x:Class="WpfApplication1.Window1"|
|2|x:Subclass|パーシャル クラスをサポートしない言語で使用...
|~|~|-|
|3|x: ClassModifier|クラスのアクセスレベルを変更する。通...
|~|~|-|
|4|x:Code|XAML上にインラインコードを実装する場合に使用す...
|~|~|<Grid>&br; <x:Code>&br; ...
|5|x:FieldModifier|プロパティのアクセスレベルを変更する。...
|~|~|-|
|6|x:Key|XAMLで定義された各種「[[リソース>#p50dd8ac]]」を...
|~|~|<Window.Resources>&br; <Style x:Key=...
|7|x:Name|XAMLで生成したCLRオブジェクトに名前を付与する。...
|~|~|<Button x:Name="button1">&br; ...
|8|x:Shared|静的な[[リソース>#p50dd8ac]]を、取得の度に生...
|~|~|-|
|9|x:TypeArguments|ジェネリックの型引数をコンストラクタに...
|~|~|<!-- XAML 2009 -->&br;<ObservableColl...
|10|x:Uid|ローカライゼーションのプロセスとツールによって...
|~|~|-|
|11|xml:lang|カルチャ情報を宣言する。|
|~|~|<Window x:Class="WpfApplication1.Window1"&br;&n...
-MSDN > Windows Presentation Foundation > グローバライズ...
http://msdn.microsoft.com/ja-jp/library/ms745650.aspx
**マークアップ拡張 [#b565ab69]
XAMLの言語機能が提供する各種「マークアップ拡張」について...
通常、「マークアップ拡張」は、「{」と「}」の2つの中括弧...
-MSDN > WPFの基礎 > WPFのXAML
--> マークアップ拡張機能とWPF XAML~
http://msdn.microsoft.com/ja-jp/library/ms747254.aspx
--> WPF XAML拡張機能~
http://msdn.microsoft.com/ja-jp/library/ms747180.aspx
***XAMLで定義されたマークアップ拡張 [#ld42b6a9]
以下、XAMLの機能である「XAMLで定義されたマークアップ拡張...
これらの種類は、中括弧+「x:」プレフィックスの直後の文字...
-XAMLに実装されたマークアップ拡張
|項番|文字列トークン|説明|h
|~|~|例|h
|1|x:Static|静的プロパティ(定数、静的プロパティ、フィー...
|~|~|<Button &br; Foreground=...
|2|x:Null|CLRオブジェクトのプロパティにnull値を設定する(...
|~|~|<Button x:Name="button1" Background="{x:Nu...
|3|x:Type|CLRクラスの型情報を指定する。|
|~|~|詳しくは、下記、項番4の例を参照のこと。|
|4|x:Array|IEnumerableを持つArrayオブジェクト(配列)を生...
|~|~|<Window.Resources>&br; <x:Array x:Ke...
※ x:Arrayは、例外的に中括弧と共に使用しない。
***WPF固有のマークアップ拡張 [#dbf77234]
以下、WPF の機能である「WPF固有のマークアップ拡張」を一覧...
こちらは、プロパティ値に「[[データ バインディング>#w4afa3...
-XAMLに実装されたマークアップ拡張
|項番|文字列トークン|説明|h
|~|~|構文 ※ 「[[プロパティ属性構文>#tb0bd2e6]]」と「[[プ...
|1|{Binding&br;・・・|Bindingオブジェクトに「バインディン...
|~|~|具体例は、「[[データ バインディングの基礎>#h0ae3316]...
|2|{StaticResource&br;・・・|既に定義された[[リソース>#p5...
|~|~|具体例は、「[[リソースとのデータ バインディング>#eb8...
|3|{DynamicResource&br;・・・|[[リソース>#p50dd8ac]]が変...
|~|~|具体例は、「[[リソースとのデータ バインディング>#eb8...
|4|{TemplateBinding&br;・・・|親コントロールに適用したプ...
|~|~|具体例は、「[[テンプレート>#o64ea160]]」を参照のこと...
|5|{RelativeSource&br;・・・|Binding.RelativeSourceを指定...
|~|~|具体例は、[[次>#b35e6e76]]を参照のこと。&br;&br;[[プ...
|6|{ThemeDictionary&br;・・・|カスタム コントロールの作成...
|~|~|-|
※ keyには、x:Keyディレクティブによって指定された既存の[[...
**マークアップ拡張の例 [#xa799e4b]
***バインディングのマークアップ拡張の例 [#vec851f2]
[[こちら>#ca5673d9]]
***TemplateBindingの例 [#hee73def]
[[こちら>#wc88b865]]
***RelativeSourceの例 [#b35e6e76]
[[こちら>#wc88b865]]
*プロパティの設定方法 [#ra4d77a1]
プロパティの設定方法として、
-[[プロパティ属性構文>#tb0bd2e6]]:~
要素の属性にテキストを使用して設定する。
-[[プロパティ要素構文>#s389a559]]:~
要素のinnerText・innerXMLを使用してプロパティを設定する。
の2つの構文について説明する。
以下、TextBox要素に対して、同等の属性を設定する~
「[[プロパティ属性構文>#tb0bd2e6]]」と「[[プロパティ要素...
**プロパティ属性構文 [#tb0bd2e6]
要素の属性にテキストを使用してプロパティを設定する方法
-プロパティ属性構文の例
<TextBox
Width = "100"
FontSize = "30"
Text = "text1"
Background = "White"
Foreground = "Blue" />
**プロパティ要素構文 [#s389a559]
要素の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>
なお、子要素のコレクションを設定する「[[プロパティ要素構...
-Panel.Childrenプロパティ
-ItemsControl.[[Itemsプロパティ>#v7960713]]
などは、暗黙的に使用されるため明記が不要のものもある。
**型コンバータ [#r36d6abd]
XAMLパーサは、XAMLの「[[プロパティ属性構文>#tb0bd2e6]]」...
プリミティブ型に変換できるリテラル文字列として解釈するか...
なお、「型コンバータ」(と、そのベース クラスであるTypeCo...
.NETのコンポーネントとコントロールのデザイン時・実行時の...
しかし、XAMLの「[[プロパティ属性構文>#tb0bd2e6]]」からのC...
XAMLパーサは通常、プロパティの型(CLRクラス)にTypeConver...
付与されている場合は、この属性値に基づいた「型コンバータ...
以下は、ユーザ コントロールに、MyPointというカスタムの型...
XAMLの「[[プロパティ属性構文>#tb0bd2e6]]」として指定され...
***カスタム型 [#p2ae99f0]
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; }
}
}
***型コンバータ [#k0c10e95]
/// <summary>カスタム型の型コンバータ</summary>
public class MyPointConverter : TypeConverter {
/// <summary>CanConvertFrom(変換可能かチェックする)<...
public override bool CanConvertFrom(
ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <summary>指定された文字列をカスタム型(MyPoint)に...
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)を文字列に...
public override object ConvertTo(ITypeDescriptorContex...
CultureInfo culture, object value, Type destinationT...
if (destinationType == typeof(string)) {
return ((MyPoint)value).X + "," + ((MyPoint)value)...
}
return base.ConvertTo(context, culture, value, desti...
}
}
***ユーザ コントロール [#gc3459c6]
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; }
}
・・・
***型コンバータの使用例 [#gc5dd259]
上記のユーザ コントロールのカスタムの型を取るCLRプロパテ...
<uc:UserControl1 x:Name="userControl1" MyLocation="10,20...
ただし、(当然ながら、)文字列からの変換をサポートしている...
文字列で表現できないプロパティ値は、「[[プロパティ属性構...
-MSDN > WPFの基礎 > WPFのXAML > TypeConverters及びXAML~
http://msdn.microsoft.com/ja-jp/library/aa970913.aspx
*コンテンツ構文 [#m4c088a5]
「コンテンツ構文」とは、[[Contentプロパティ>#gc84bde8]](...
-ContentPropertyAttributeを付けることで、
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.ma...
---[ContentPropertyAttribute("Content")] → [[Contentプロ...
---[ContentPropertyAttribute("Items")] → [[Itemsプロパテ...
-属性に指定される[[Contentプロパティ>#gc84bde8]]を、~
innerText・innerXML([[プロパティ要素構文>#s389a559]])と...
--コンテンツ構文
---[[プロパティ属性構文>#tb0bd2e6]]
<Button Content="Click Here" />
---[[プロパティ要素構文>#s389a559]]
<Button>Click Here</Button>
-比較
--なお、[[Windows Forms]]や[[Web Forms>ASP.NET Web Forms]...
UIコントロールの「[[スタイル>#v30d5ab6]]」属性の指定によ...
--これに対し、WPFのUIコントロールは「[[スタイル>#v30d5ab6...
[[Contentプロパティ>#gc84bde8]](または[[Itemsプロパティ>...
コントロールの「外観」を自由に変更でき、柔軟性が非常に高...
-補足:Windowsフォームの外観の変更
--コントロールを自前で描画する「オーナー描画」と呼ばれる...
「オーナー描画」はグラフィックス メソッドなどを使用して、~
すべての描画を独自に行わなければならないため、深い知識と...
--関連資料
---[[.NETコントロールのカスタマイズ方法]]
**Contentプロパティ [#gc84bde8]
WPFのContentControlは、
-ContentControl.Contentプロパティに設定された単一の要素を...
-ContentControl.Contentプロパティに任意の型の子要素を設定...
-従って、ContentControlを継承するButtonクラスやLabelクラ...
--Control.Templateプロパティ
--ContentControl.ContentTemplateプロパティ
***文字列のコンテンツ要素を格納 [#m12672f2]
WPFのContentControlのButtonコントロールを例にしてContent...
-XAML
--[[プロパティ属性構文>#tb0bd2e6]]:
<Button Width="200" Height="200" Content="ボタン"/>
--[[プロパティ要素構文>#s389a559]]:
<Button Width="200" Height="200">ボタン</Button>
-レンダリング結果
#ref(ContentString.png,left,nowrap,文字列のコンテンツ要素...
***イメージのコンテンツ要素を格納 [#faf81a9f]
Contentプロパティには、Imageオブジェクトなどの任意の型の...
-XAML
<Button Width="200" Height="200">
<Button.Content>
<Image Source=".\Blue hills.jpg"/>
</Button.Content>
</Button>
-レンダリング結果
#ref(ContentImage.png,left,nowrap,イメージのコンテンツ要...
***パネルに纏めて格納した複数のコンテンツ要素 [#a73fa28e]
-XAML
--2つ以上の要素を設定したい場合は、パネル要素を使用する。
<Button Width="200" Height="200">
<Button.Content>
<StackPanel Orientation="Vertical">
<Image Source=".\Blue hills.jpg" Margin="5" />
<TextBlock Text="ボタン" HorizontalAlignment="Cent...
</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...
</StackPanel>
</Button>
-レンダリング結果
#ref(ContentStringAndImage.png,left,nowrap,パネルに纏めて...
**Itemsプロパティ [#v7960713]
WPFのItemsControlは、Itemsプロパティに任意の型の子要素を...
***複数のパネルに纏めて格納した複数のコンテンツ要素 [#w0e...
ItemsControlのItemsプロパティへは、複数のコンテンツを追加...
以下、ListBoxコントロールを例にしてItemsプロパティへ子要...
-XAML
<Grid>
<ListBox>
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Source=".\Blue hills.jpg" Height="100"/>
<TextBlock Text="Blue hills" VerticalAlignment="...
</StackPanel>
</Border>
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Source=".\Sunset.jpg" Height="100"/>
<TextBlock Text="Sunset" VerticalAlignment="Cent...
</StackPanel>
</Border>
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Source=".\Water lilies.jpg" Height="100"/>
<TextBlock Text="Water lilies" VerticalAlignment...
</StackPanel>
</Border>
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Source=".\Winter.jpg" Height="100"/>
<TextBlock Text="Winter" VerticalAlignment="Cent...
</StackPanel>
</Border>
</ListBox>
</Grid>
-レンダリング結果
#ref(ItemsControl.png,left,nowrap,複数のパネルに纏めて格...
-説明
--Itemsプロパティに子要素を設定する場合は、~
innerText・innerXMLを使用する「[[プロパティ要素構文>#s389...
---また、この際に<Object.Items>タグは省略することもできる。
--ちなみに、上記を「[[データ バインディング>#w4afa32c]]」...
---これについては、「[[データ バインディングの基礎>#h0ae3...
*リソース [#p50dd8ac]
ここでは、
-「リソース」の定義方法と、
-前述の各「[[マークアップ拡張>#b565ab69]]」を使用し、~
プロパティ値に「リソース」への参照を指定する方法
について説明する。
※「リソース」の「[[データ バインディング>#w4afa32c]]」に...
「[[リソースとのデータ バインディング>#eb81566f]]を参照の...
-参考
--MSDN > WPFの基礎 > リソース~
http://msdn.microsoft.com/ja-jp/library/ms742538.aspx
**リソースの定義 [#g7e2fd50]
「リソース」とは、ResourceDictionary 型のオブジェクトであ...
-ApplicationオブジェクトのResources プロパティ
-各UI要素(FrameworkElement or FrameworkContentElement)...
に「[[プロパティ要素構文>#s389a559]]」を使用して定義でき...
-MSDN > .NET Frameworkクラス ライブラリ
-- > System.Windows.ResourceDictionaryクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.re...
-- > System.Windows.Application.Resourcesプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.ap...
-- > System.Windows.FrameworkElement.Resourcesプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.fr...
-- > System.Windows.FrameworkContentElement.Resourcesプロ...
http://msdn.microsoft.com/ja-jp/library/system.windows.fr...
このため、任意のUI要素に定義可能であるが、~
通常はルート要素(Window or Page)上に定義する。~
また、「リソース」は、定義場所により以下のような呼称・特...
***リソースの定義場所 [#qe6a5b64]
-アプリケーション リソース~
ApplicationオブジェクトのResourcesプロパティに定義された...
「アプリケーション リソース」と呼び、全体から(つまりどこ...
-ウィンドウ ページ リソース~
Window・PageオブジェクトのResourcesプロパティに定義された...
「アプリケーション リソース」と呼び、そのWindow・Pageと、...
-イミディエイト リソース~
各UI要素(FrameworkElement or FrameworkContentElement)の~
Resourcesプロパティに定義された「リソース」を「イミディエ...
「リソース」を定義した要素と、その子要素から参照できると...
***リソースの定義例 [#sedc736a]
-「リソース」には、前述のx:Key ディレクティブを使用して一...
<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>
>※ 先頭で、String型のインポートが必要~
xmlns:sys="clr-namespace:System;assembly=mscorlib"
-補足:ジェネリック コレクションのリソース~
ジェネリック コレクションを「リソース」に定義するには、x:...
ObservableCollection<T>コレクション クラスなどのジェネリ...
これは、XAML2009 からのサポートとなる。
***リソースの使用方法 [#r6badd32]
「リソース」を定義したら、各種「[[マークアップ拡張>#b565a...
プロパティ値に「[[データ バインディング>#w4afa32c]]」や、...
この時、参照する側からx:Key ディレクティブを使用して割り...
なお、「[[スタイル>#v30d5ab6]]」や「[[テンプレート>#o64ea...
指定の型のオブジェクトに「[[スタイル>#v30d5ab6]]」や「[[...
これについては、「[[スタイルとテンプレート>#j0c577be]]」...
-MSDN > .NET Frameworkクラス ライブラリ
-- > System.Windows.Style.TargetType プロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.st...
-- > System.Windows.Controls.ControlTemplate.TargetTypeプ...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
**リソースの定義と参照 [#wd960230]
以下、「リソース」の定義と、プロパティ値に「リソース」へ...
***StaticResource参照の例 [#ybb9b94a]
StaticResource参照では、
-コンパイル時に「リソース」検索が行われ、各「リソース」に...
-「リソース」検索により、「リソース」が発見できなかった場...
以下は、StaticResourceの定義と参照例。
-XAML
--StaticResourceの定義と参照例(1)
---以下は、「[[マークアップ拡張>#b565ab69]]」を使用して、...
---また、属性名を省略すると自動的にコンストラクタに渡され...
ResourceKey属性に指定の値を渡す旨を指示する「ResourceKey=...
>
<Window.Resources>
<SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
</Window.Resources>
<Grid>
<Ellipse Fill="{StaticResource ResourceKey=BlueBrush}"...
</Grid>
>↓ 「ResourceKey =」という記述を省略
>
<Window.Resources>
<SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
</Window.Resources>
<Grid>
<Ellipse Fill="{StaticResource BlueBrush}" Height="150...
</Grid>
--StaticResourceの定義と参照例(2)~
以下は、一般的ではないが「[[プロパティ要素構文>#s389a559]...
なお、WPFのみ、StaticResource参照を「[[プロパティ要素構文...
<Window.Resources>
<SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
</Window.Resources>
<Grid>
<Ellipse Height="150" Width="150">
<Ellipse.Fill>
<StaticResource ResourceKey="BlueBrush"/>
</Ellipse.Fill>
</Ellipse>
</Grid>
-レンダリング結果
#ref(StaticResource.png,left,nowrap,StaticResourceの定義...
***DynamicResource参照の例 [#h04a05da]
-DynamicResource参照では、アプリケーションの起動時に、~
後で「リソース」検索を行う際に使用する一時的な式が作成さ...
アプリケーションの実行後、「リソース」が必要になった際に...
-このためDynamicResource参照は、
--主に「リソース」の値が変更される場合、StaticResource参...
--「リソース」検索により、「リソース」が発見できなかった...
-なお、DynamicResource参照は、WPFでのみ利用可能で、「Silv...
以下は、DynamicResourceの定義と参照例。
-以下は、リソースがアプリケーション外部から変更される場合...
以下は、デスクトップ画面のテーマの変更(Windows XP → Wind...
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Ellipse Grid.Row="0"
Fill="{StaticResource ResourceKey={x:Static SystemCo...
<Ellipse Grid.Row="1"
Fill="{DynamicResource ResourceKey={x:Static SystemC...
</Grid>
#ref(DynamicResource1.png,left,nowrap,DynamicResourceの定...
-以下は、リソースがアプリケーション内部から変更される場合...
以下は、アプリケーションからの「リソース」の動的な変更を...
なお、「リソース」の動的な変更は、FrameworkElement.Resour...
--XAML
<Window.Resources>
<SolidColorBrush x:Key="MyBrush" Color="Blue"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition Height="23"/>
</Grid.RowDefinitions>
<Ellipse Grid.Row="0" Fill="{StaticResource MyBrush}"/>
<Ellipse Grid.Row="1" Fill="{DynamicResource MyBrush}"/>
<StackPanel Grid.Row="2" Orientation="Horizontal" Hori...
<Button Content="青" Height="23" Name="button1" Widt...
<Button Content="赤" Height="23" Name="button2" Widt...
</StackPanel>
</Grid>
--コード ビハインド
private void button1_Click(object sender, RoutedEventArg...
this.Resources["MyBrush"] = Brushes.Blue;
}
private void button2_Click(object sender, RoutedEventArg...
this.Resources["MyBrush"] = Brushes.Red;
}
#ref(DynamicResource2.png,left,nowrap,DynamicResourceの定...
***StaticResource参照 + ディクショナリ ファイルの例 [#k80...
ResourceDictionaryは、「ディクショナリ ファイル」に定義す...
「ディクショナリ ファイル」を追加する際は、
+プロジェクト ファイルを右クリックし、
+[追加] → [リソース ディクショナリ]を選択するか、~
[追加] → [新しい項目]を選択し、表示される[[テンプレート>#...
#ref(AddDictionary.png,left,nowrap,ディクショナリ ファイ...
-前述のStaticResource参照の例を、~
「ディクショナリ ファイル」を使用するように書き直した例を...
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="BlueBrush" Color="Blue"/>
</ResourceDictionary>
''ディクショナリ ファイルの定義例 (Dictionary1.xaml)''
-「ディクショナリ ファイル」を「イミディエイト・リソース...
<Window.Resources>
<ResourceDictionary Source="Dictionary1.xaml"/>
</Window.Resources>
<Grid>
<Ellipse Fill="{StaticResource BlueBrush}" Height="150...
</Grid>
>
#ref(StaticResourceAndDictionary.png,left,nowrap,StaticRe...
''StaticResource参照 + ディクショナリ ファイルの使用例''
***DynamicResource参照 + ディクショナリ ファイルの例 [#z0...
-DynamicResource参照とResourceDictionaryを組み合わせ、
-ResourceDictionaryを、Application.LoadComponentで動的に...
-Application.Current.Resourcesに設定することにより、
-「[[スタイル>#v30d5ab6]]」(スキン )などの設定をアプリ...
以下の、その例を示す。
-Dictionary
--Dictionary1.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="MyBrush" Color="Blue"/>
</ResourceDictionary>
--Dictionary2.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/pr...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="MyBrush" Color="Red"/>
</ResourceDictionary>
-XAML
<StackPanel>
<Ellipse Fill="{DynamicResource MyBrush}" Height="150"...
<Button Content="青" Height="23" Name="button1" Width=...
<Button Content="赤" Height="23" Name="button2" Width=...
</StackPanel>
-コード ビハインド
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
this.LoadResourceDictionary("Dictionary1.xaml");
}
private void button1_Click(object sender, RoutedEventA...
this.LoadResourceDictionary("Dictionary1.xaml");
}
private void button2_Click(object sender, RoutedEventA...
this.LoadResourceDictionary("Dictionary2.xaml");
}
private void LoadResourceDictionary(string name) {
ResourceDictionary dictionary =
(ResourceDictionary)Application.LoadComponent(new ...
if (dictionary != null) Application.Current.Resource...
}
}
>
#ref(DynamicResourceAndDictionary.png,left,nowrap,Dynamic...
''DynamicResource参照 + ディクショナリ ファイルの使用例''
*データ バインディング [#w4afa32c]
様々なソースと「データ バインディング」するサンプルを示す。
なお、サンプルのXAMLソースを読むためには、以下の、~
Bindingプロパティの設定方法を理解しておく必要がある。
''Bindingプロパティの設定方法''
|項番|プロパティ|説明|h
|1|Mode|OneTime、OneWay、TwoWay のいずれかの「バインディ...
|2|Source|「バインディング ソース」を指定する。「バイン...
|3|ElementName|UI要素名を使用して「バインディング ソース...
|4|[[RelativeSource>#b35e6e76]]|「バインディング ターゲ...
|5|Path|「バインディング ソース」のプロパティ名を指定す...
|6|XPath|「バインディング ソース」として、XMLデータソー...
|7|TargetNullValue|ソース値が null のときに返される値を...
|8|Converter|「[[値コンバータ>WPFのアーキテクチャ#nf7e2b...
|9|ConverterCulture|「[[値コンバータ>WPFのアーキテクチャ...
|10|ConverterParameter|「[[値コンバータ>WPFのアーキテクチ...
-MSDN > ・・・ > バインディングのマークアップ拡張機能~
http://msdn.microsoft.com/ja-jp/library/ms750413.aspx
--MSDN > ・・・ > PropertyPathのXAML構文~
http://msdn.microsoft.com/ja-jp/library/ms742451.aspx
--MSDN > ・・・ > 方法:XMLDataProviderとXPathクエリを試...
http://msdn.microsoft.com/ja-jp/library/ms749287.aspx
**データ バインディングの基礎 [#h0ae3316]
以下、「[[WPFのアーキテクチャ - データ バインディング>WPF...
***コード ビハインドからのデータ バインディング(モード:...
-モード:OneWayの「データ バインディング」を行う。
-「データ バインディング」の基本的な動作を理解するために、
--Bindingオブジェクトをコード ビハインドで自作し、
--以下の2つのオブジェクトを結びつける。
---「バインディング ソース」
---「バインディング ターゲット」
-XAML
<StackPanel
x:Name="MainPanel"
Loaded="MainPanel_Loaded">
<TextBlock x:Name="TextBlock1"/>
<TextBlock x:Name="TextBlock2"/>
</StackPanel>
-コード ビハインド
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
}
private void MainPanel_Loaded(object sender, RoutedEve...
{
// バインディング ソース(Person)
Person BindingSource =
new Person() { Height = 1.7, Weight = 60 };
// Bindingオブジェクトによりバインド
// HeightプロパティをOneWayでバインド
Binding BindingHeight = new Binding("Height");
BindingHeight.Mode = BindingMode.OneWay;
// バインディング ソース(Person)
BindingHeight.Source = BindingSource;
// バインディング ターゲット(TextBlock)
TextBlock1.SetBinding(TextBlock.TextProperty, Bindin...
// WeightプロパティをOneWayでバインド
Binding BindingWeight = new Binding("Weight");
BindingWeight.Mode = BindingMode.OneWay;
// バインディング ソース(Person)
BindingWeight.Source = BindingSource;
// バインディング ターゲット(TextBlock)
TextBlock2.SetBinding(TextBlock.TextProperty, Bindin...
}
}
/// <summary>バインディング ソース(Person)</summary>
public class Person {
public double Height { get; set; }
public double Weight { get; set; }
}
***コード ビハインドからのDataContextを使用したデータ バ...
上記のMainPanel_Loadedメソッドのコードを一部編集し、MainP...
FrameworkElement.DataContextプロパティに「バインディング ...
Bindingオブジェクトへの「バインディング ソース」の指定が...
-コード ビハインド
private void MainPanel_Loaded(object sender, RoutedEvent...
// バインディング ソース(Person)
MainPanel.DataContext =
new Person() { Height = 1.7, Weight = 60 };
// Bindingオブジェクトによりバインド
// HeightプロパティをOneWayでバインド
Binding BindingHeight = new Binding("Height");
BindingHeight.Mode = BindingMode.OneWay;
// バインディング ターゲット(TextBlock)
this.TextBlock1.SetBinding(TextBlock.TextProperty, Bin...
// WeightプロパティをOneWayでバインド
Binding BindingWeight = new Binding("Weight");
BindingWeight.Mode = BindingMode.OneWay;
// バインディング ターゲット(TextBlock)
TextBlock2.SetBinding(TextBlock.TextProperty, BindingW...
}
***BindingオブジェクトをXAMLで実装する([[プロパティ要素...
-BindingオブジェクトをXAMLのマークアップ機能で実装する。~
更に、XAMLのマークアップ機能を使用して、Bindingオブジェク...
上記のXAMLとMainPanel_Loadedメソッドのコードを一部編集し...
--XAML
<StackPanel
x:Name="MainPanel"
Loaded="MainPanel_Loaded">
<TextBlock>
<TextBlock.Text>
<Binding Path="Height" Mode="OneWay"/>
</TextBlock.Text>
</TextBlock>
<TextBlock>
<TextBlock.Text>
<Binding Path="Weight" Mode="OneWay"/>
</TextBlock.Text>
</TextBlock>
</StackPanel>
--コード ビハインド
private void MainPanel_Loaded
(object sender, RoutedEventArgs e) {
// バインディング ソース(Person)
MainPanel.DataContext =
new Person() { Height = 1.7, Weight = 60 };
}
***Bindingオブジェクトをバインディングのマークアップ拡張...
-一般的には、「データ バインディング」を実装する場合、XAM...
「バインディングのマークアップ拡張」により「[[プロパティ...
-上記のXAMLを「バインディングのマークアップ拡張」を使用し...
<StackPanel x:Name="MainPanel" Loaded="MainPanel_Loaded">
<TextBlock Text="{Binding Path=Height, Mode=OneWay}" />
<TextBlock Text="{Binding Path=Weight, Mode=OneWay}" />
</StackPanel>
-また、属性名を省略すると自動的にコンストラクタに渡される...
(Path属性に指定の値を渡す旨を指示する)「Path=」という記...
<StackPanel x:Name="MainPanel" Loaded="MainPanel_Loaded">
<TextBlock Text="{Binding Height, Mode=OneWay}" />
<TextBlock Text="{Binding Weight, Mode=OneWay}" />
</StackPanel>
***変更通知の追加(モード:OneWay or OneWayToSource) [#i...
下記は、モード:OneWay or OneWayToSourceを併用した「デー...
この例では、「バインディング ソース」のプロパティ値の変更...
なお、この際、「バインディング ソース」は、INotifyPropert...
-XAML
<StackPanel x:Name="MainPanel" Loaded="MainPanel_Loaded">
<TextBox Margin="10" Text="{Binding Height, Mode=OneWa...
<TextBox Margin="10" Text="{Binding Weight, Mode=OneWa...
<Button Margin="10" Content="計算" Click="Button_Click...
<TextBlock Margin="10" Text="{Binding Bmi, Mode=OneWay...
</StackPanel>
-コード ビハインド
/// <summary>/// Window1.xaml の相互作用ロジック/// </su...
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
}
/// <summary>初期化イベント</summary>
private void MainPanel_Loaded(object sender, RoutedEve...
// バインド ソース(Person)
MainPanel.DataContext = new Person();
}
/// <summary>計算イベント</summary>
private void Button_Click(object sender, RoutedEventAr...
((Person)MainPanel.DataContext).Calculate();
}
}
-バインディングソース
/// <summary>バインド ソース(Person)</summary>
public class Person : INotifyPropertyChanged {
public double Height { get; set; }
public double Weight { get; set; }
double _bmi;
public double Bmi {
get { return this._bmi; }
set {
this._bmi = value;
// 変更通知
this.OnPropertyChanged("Bmi");
}
}
/// <summary>計算処理</summary>
public void Calculate() {
this.Bmi = Weight / Math.Pow(Height, 2);
}
#region INotifyPropertyChanged メンバ
/// <summary>値変更イベントの定義</summary>
public event PropertyChangedEventHandler PropertyChang...
/// <summary>変更通知(値変更イベントを発生させる)</s...
protected virtual void OnPropertyChanged(string proper...
PropertyChangedEventHandler handler = this.PropertyC...
if (handler != null)
handler(this, new PropertyChangedEventArgs(propert...
}
#endregion
}
***値コンバータを使用したデータ バインディング(モード:O...
続いて、上記処理に、BMI(肥満度)プロパティが
-18.5未満の場合、出力先のTextBlockの背景色を青色に
-25以上の場合、出力先のTextBlockの背景色を赤色に
変更する処理を追加する。
これには別途、背景色プロパティを定義することで実現するこ...
ここでは、前述のIValueConverterインターフェイスを実装した...
値の変換処理は、「値コンバータ」のConvertメソッドに実装す...
-XAML
<Window.Resources>
<my:BmiLevelConverter x:Key="bmiLevelConverter"/>
</Window.Resources>
<StackPanel x:Name="MainPanel" Loaded="MainPanel_Loaded">
<TextBox Margin="10" Text="{Binding Height, Mode=OneWa...
<TextBox Margin="10" Text="{Binding Weight, Mode=OneWa...
<Button Margin="10" Content="計算" Click="Button_Click...
<TextBlock Margin="10"
Text="{Binding Bmi, Mode=OneWay}"
Background="{Binding Bmi, Mode=OneWay,
Converter={StaticResource bmiLevelConverter}}"/>
</StackPanel>
-値コンバータ
/// <summary>BMIレベルに合った背景色を返す</summary>
public class BmiLevelConverter : IValueConverter {
#region IValueConverter メンバ
/// <summary>変換メソッド(ソースからターゲット)</sum...
public object Convert(object value, Type targetType, o...
// BMIレベルに合った背景色を返す
double target = (double)value;
SolidColorBrush level;
if (target < 18.5)
level = new SolidColorBrush(Colors.Blue);
else if (target > 25)
level = new SolidColorBrush(Colors.Red);
else
level = new SolidColorBrush(Colors.White);
return level;
}
/// <summary>変換メソッド(ターゲットからソース)</sum...
public object ConvertBack(object value, Type targetTyp...
throw new NotImplementedException();
}
#endregion
}
***INotifyPropertyChangedの変更通知を「依存関係プロパティ...
なお、変更通知は、INotifyPropertyChangedインターフェイス...
上記の例のBMI(肥満度)プロパティを「依存関係プロパティ」...
-バインディングソース
/// <summary>バインド ソース(Person)</summary>
public class Person : DependencyObject {
public double Height { get; set; }
public double Weight { get; set; }
/// <summary>Bmiプロパティを依存関係プロパティとして登...
public static readonly DependencyProperty BmiProperty =
DependencyProperty.Register("Bmi", typeof(double), t...
new UIPropertyMetadata(0.0));
/// <summary>BmiプロパティのCLRプロパティ</summary>
public double Bmi {
get { return (double)this.GetValue(Person.BmiPropert...
set { this.SetValue(Person.BmiProperty, value); }
}
/// <summary>計算処理</summary>
public void Calculate(){
this.Bmi = Weight / Math.Pow(Height, 2);
}
}
BMI(肥満度)プロパティが変更されると、UI要素(TextBlock...
このように、「依存関係プロパティ」は既定で変更通知をサポ...
***双方向のデータ バインディング(モード:TwoWay) [#q577...
以下の例では、モード:TwoWayの「データ バインディング」を...
2つのUI要素、TextBoxとSliderを双方向接続した例である。
なお前述のようにUI要素の表示に関するプロパティは、~
基本的に「依存関係プロパティ」として定義されており、~
既定で変更通知をサポートしている。このため、既定で双方向...
なお、「バインディング ソース」をUI要素に接続する場合は、...
-TextBox(ソース)→Slider(ターゲット)
--XAML
<StackPanel Orientation="Vertical">
<Label>TextBox</Label>
<TextBox x:Name="textBox1" Text="5"/>
<Rectangle Height="20"></Rectangle>
<Label>Slider</Label>
<Slider x:Name="Slider1"
Value="{Binding ElementName=textBox1, Path=Text, Mod...
</StackPanel>
-Slider(ソース)→TextBox(ターゲット)
--バインディング ソース、バインディング ターゲットを反転...
--すると「バインディング ターゲット」(TextBox)の変更が...
(TextBoxから、フォーカスが外れないとSliderに変更値が反映...
--これは、ほとんどの依存関係プロパティの既定値は Property...
--この場合、「バインディングのマークアップ拡張」に、「Upd...
「バインディング ターゲット」(TextBox)からの変更が直ち...
--XAML
<StackPanel Orientation="Vertical">
<Label>TextBox</Label>
<TextBox x:Name="textBox1"
Text="{Binding ElementName=Slider1, Path=Value, Mode...
<Rectangle Height="20"></Rectangle>
<Label>Slider</Label>
<Slider x:Name="Slider1" Value="5"/>
</StackPanel>
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
---UpdateSourceTriggerプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.da...
---UpdateSourceTrigger列挙体~
http://msdn.microsoft.com/ja-jp/library/system.windows.da...
***値コンバータを使用したデータ バインディング(モード:T...
双方向の値の変換に対応した「値コンバータ」は、~
Convert、ConvertBackメソッドの双方を実装する必要がある。
-XAML
<Window.Resources>
<my:ValConverter x:Key="valConverter" />
</Window.Resources>
<StackPanel Orientation="Vertical">
<Label>TextBox</Label>
<TextBox x:Name="textBox1" Text="500"/>
<Rectangle Height="20"></Rectangle>
<Label>Slider</Label>
<Slider x:Name="Slider1"
Value="{Binding ElementName=textBox1, Path=Text, Mod...
Converter={StaticResource valConverter}}"/>
</StackPanel>
-コード ビハインド
public class ValConverter : IValueConverter {
#region IValueConverter メンバ
/// <summary>変換メソッド(ソースからターゲット)</sum...
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo c...
return int.Parse(value.ToString()) / 100;
}
/// <summary>変換メソッド(ターゲットからソース)</sum...
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo c...
return ((double)value) * 100;
}
#endregion
}
***ItemsSourceへのデータ バインディング [#qe911f6c]
ItemsControlから派生した要素のItemsSource属性にコレクショ...
-ItemsSourceへのデータ バインディング(UI要素を含まない「...
以下は、ObservableCollection<T> コレクション クラスを使用...
なお、ObservableCollection<T>コレクション クラスは、INoti...
--XAML
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="listBox1" ItemsSource="{Binding}"/>
<Button Height="23" Name="button1" Click="button1_Clic...
</StackPanel>
--コード ビハインド
public partial class Window1 : Window {
ObservableCollection<string> _cities = new ObservableC...
public Window1() {
InitializeComponent();
this._cities.Add("札幌市");
this._cities.Add("仙台市");
this._cities.Add("静岡市");
this.stackPanel1.DataContext = _cities;
}
private void button1_Click(object sender, RoutedEventA...
this._cities.Add("神戸市" + this.listBox1.Items.Coun...
}
}
--UI要素を含まない「データ バインディング」の実装例につい...
---上記例では、button1_ClickイベントでItemがObservableCol...
また、この変更通知をサポートしているObservableCollection<...
Collection<T>コレクションに追加されたItemがListBoxの表示...
---なお、変更通知に対応したカスタム コレクションを作成す...
ObservableCollection<T>や、Collection<T> & INotifyCollect...
---この際の注意点としては、後者のCollection<T> & INotifyC...
Add、RemoveAtなどのメソッドに変更通知を実装し、「変更通知...
前述のPropertyChangedEventHandlerではなく、NotifyCollecti...
-ItemsSourceへのデータ バインディング(UI要素を含んだ「デ...
以下は、[[「Itemsプロパティ」>#v7960713]]の例を「データ ...
--XAML
<StackPanel x:Name="stackPanel1">
<ListBox ItemsSource="{Binding}"/>
</StackPanel>
--コード ビハインド
public Window1() {
InitializeComponent();
// バンディング ソース(コレクション)
ObservableCollection<Border> cities = new ObservableCo...
// ワーク
Border tmpBorder = null;
StackPanel tmpStackPanel = null;
Image tmpImage = null;
TextBlock tmpTextBlock = null;
// Borderの構築
tmpBorder = new Border();
tmpBorder.BorderBrush = Brushes.Black;
tmpBorder.BorderThickness = new Thickness(1);
tmpBorder.Margin = new Thickness(5);
// StackPanelの構築
tmpStackPanel = new StackPanel();
tmpStackPanel.Orientation = Orientation.Horizontal;
tmpStackPanel.Height = 120;
tmpStackPanel.Width = 250;
tmpStackPanel.Margin = new Thickness(5);
// Imageの構築
tmpImage = new Image();
tmpImage.Source=new BitmapImage(
new Uri(@".\Water lilies.jpg", UriKind.Relative));
tmpImage.Height=100;
// TextBlockの構築
tmpTextBlock = new TextBlock();
tmpTextBlock.Text="Water lilies";
tmpTextBlock.VerticalAlignment = VerticalAlignment.Cen...
// 階層構造の組み立て
tmpStackPanel.Children.Add(tmpImage);
tmpStackPanel.Children.Add(tmpTextBlock);
tmpBorder.Child = tmpStackPanel;
// バンディング ソース(コレクション)に追加
cities.Add(tmpBorder);
// ・・・(n項繰り返し)・・・
// データ バンディング
stackPanel1.DataContext = cities;
}
--UI要素を含んだ「データ バインディング」の実装例について、
---子要素を持つUI要素をコード ビハインドで作成し、これを...
---このような場合は、「[[テンプレート>#o64ea160]]」を使用...
---「[[テンプレート>#o64ea160]]」を使用した実装例は、「[[...
***インデクサによるデータ バインディング [#t27b49c9]
インデクサについても、Path属性に角括弧を指定することで接...
-XAML
<Grid>
<Image x:Name="Image1"
Height="200" Width="200"
Source="{Binding Path=[Source]}"
ToolTip="{Binding Path=[ToolTip]}"/>
</Grid>
-コード ビハインド
public Window1() {
InitializeComponent();
Hashtable ht = new Hashtable();
ht["Source"] = @".\Winter.jpg";
ht["ToolTip"] = "Winter";
this.Image1.DataContext = ht;
}
これらを応用すると、~
インデクサを持つオブジェクトの配列(反復処理をサポート)~
をデータ バインディングすることも可能であることが分かる。
ビジネス・アプリケーションでは、DataGridへDataTableをデー...
DataGridの列へDataTableの列をマッピングするようなケースで...
**[[リソース>#p50dd8ac]]とのデータ バインディング [#eb815...
「[[リソース>#p50dd8ac]]」参照を「バインディングのマーク...
***StaticResourceを使用したデータ バインディング [#q416a6...
-例えば、静的な「[[リソース>#p50dd8ac]]」を使用し、以下の...
--StaticResourceのデータ バインディング (1)
<Window.Resources>
<sys:String x:Key="val">Click Here</sys:String >
</Window.Resources>
<StackPanel>
<Button Content="{Binding Source={StaticResource val}}...
</StackPanel>
>※ 先頭で、String型のインポートが必要~
xmlns:sys="clr-namespace:System;assembly=mscorlib"
-ItemsControlから派生したUIコントロールのItemsSource属性...
「[[リソース>#p50dd8ac]]」の対象オブジェクトは反復処理を...
--StaticResourceのデータ バインディング (2)
<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 ...
</StackPanel>
>※ 先頭で、String型のインポートが必要~
xmlns:sys="clr-namespace:System;assembly=mscorlib"
***DynamicResourceを使用したデータ バインディング [#e0022...
動的な「[[リソース>#p50dd8ac]]」を使用した「データ バイン...
以下、「{Binding Source={DynamicResource」をテストした際...
型 'Binding' の 'Source' プロパティで 'DynamicResourceEx...
-参考
--MSDN > .NET Frameworkクラス ライブラリ
--- > System.Windows.Data.Binding.Sourceプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.da...
--- > System.Windows.DynamicResourceExtensionクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.dy...
*レイアウト [#lc8aa2dd]
ココでは、レイアウト方法として、
-[[レイアウトのプロパティ>#ad27e006]]
-[[パネルの種類と使い方>#t2926641]]
の2つについて説明する。
-MSDN > WPFの基礎 > レイアウト システム~
http://msdn.microsoft.com/ja-jp/library/ms745058.aspx
**レイアウトのプロパティ [#ad27e006]
-ココでは、「レイアウト」関係のプロパティについて説明する。
-これらのプロパティは、「レイアウト」機能を追加するFramew...
--配置の際、各要素間に余白を指定したい場合は、Margin、Pad...
---Margin :自要素と親要素の間
---Padding:自要素と子要素の間~
※ [left, top, right, bottom]と設定可能。省略時の動作は、...
--配置の際、「揃え」を指定したい場合は、HorizontalAlignme...
---HorizontalAlignment :水平方法の揃え(Center、Left、Ri...
---VerticalAlignment :垂直方法の揃え(Center、Top、Bot...
※ Stretchは、引き伸ばして余白を埋めて配置の意味。
-以下、「レイアウト」関係のプロパティを使用したXAMLとレン...
--XAML
<Border Background="LightBlue" BorderBrush="Black" Borde...
<StackPanel Background="White" HorizontalAlignment="Ce...
<TextBlock Margin="5,0,5,0" HorizontalAlignment="Cen...
<Button HorizontalAlignment="Left" Margin="20">Butto...
<Button HorizontalAlignment="Right" Margin="10">Butt...
<Button HorizontalAlignment="Stretch" Margin="0">But...
</StackPanel>
</Border>
--[[レンダリング>https://i-msdn.sec.s-msft.com/dynimg/IC1...
-参考
--MSDN > WPFの基礎 > 基本要素 > 配置、余白、パディングの...
http://msdn.microsoft.com/ja-jp/library/ms751709.aspx
**パネルの種類と使い方 [#t2926641]
WPFでは、パネルを使用した「レイアウト」が可能である。
-パネルには、以下のような特徴がある。
--複数のUIElementを含めることができる(UIElementCollectio...
---MSDN > .NET Frameworkクラス ライブラリ > System.Window...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
>UIElement子要素の順序付けられたコレクションを表す。~
XAMLから「[[プロパティ要素構文>#s389a559]]」の「[[コンテ...
<Panel.Children>タグを使用する(ただし、このタグを...
また、コード ビハインドから、パネル要素に子要素を追加する...
--自分に含まれるUIElementを管理する。
--パネル自体もUIElementであるため、パネルへの組み込みが可能
-使用可能なパネル要素には次のものがある。
|#|パネル名|クラス名|説明|h
|1|キャンバス パネル|Canvas|座標を使用して子要素を明示的...
|2|ドック パネル|DockPanel|パネルの各「辺」に、子要素をド...
|3|スタック パネル|StackPanel|子要素を水平方向または垂直...
|4|折り返しパネル|WrapPanel|子要素を水平方向または垂直方...
|5|(均一)グリッド パネル|UniformGrid|列と行で構成されて...
|6|グリッド パネル|Grid|列と行で構成されている柔軟なグリ...
-また、親要素であるパネルへ配置する子要素の座標などの情報...
子要素から「添付プロパティ」を使用して設定可能である。
***キャンバス パネル [#p5a51a2b]
-座標を使用して子要素を明示的に配置できる領域を定義する。
--XAML
<Canvas Background="LightSteelBlue">
<TextBlock Canvas.Top="10" Canvas.Left="20">
Hello World!
</TextBlock>
<TextBlock Canvas.Top="40" Canvas.Left="50">
絶対位置決め方式は便利ではありませんか?
</TextBlock>
</Canvas>
--レンダリング結果
#ref(RenderingResultOfCanvas.png,left,nowrap,キャンバス ...
-キャンバス パネルでは、「添付プロパティ」であるCanvas.To...
子要素から座標位置を明示的に指定・配置できるため、Windows...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***ドック パネル [#pe1b48eb]
-パネルの各「辺」に、子要素をドッキングする領域を定義する。
--XAML
<DockPanel LastChildFill="True">
<Border Height="25" Background="SkyBlue" DockPanel.Doc...
<TextBlock Foreground="Black">Dock = "Top(1)"</Te...
</Border>
<Border Height="25" Background="SkyBlue" DockPanel.Doc...
<TextBlock Foreground="Black">Dock = "Top(2)"</Te...
</Border>
<Border Height="25" Background="LemonChiffon" DockPane...
<TextBlock Foreground="Black">Dock = "Bottom"</TextB...
</Border>
<Border Width="100" Background="PaleGreen" DockPanel.D...
<TextBlock Foreground="Black">Dock = "Left"</TextBlo...
</Border>
<Border Background="White">
<TextBlock Foreground="Black">
This content will "Fill" the remaining space
</TextBlock>
</Border>
</DockPanel>
--レンダリング結果
#ref(RenderingResultOfDockPanel.png,left,nowrap,ドック パ...
-DockPanel.LastChildFillプロパティ(LastChildFill属性)を...
DockPanelの最終の子要素は常に残りの領域を埋めるようになる。
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***スタック パネル [#i49c2e00]
-子要素を水平方向または垂直方向に整列する領域を定義する。
--XAML
---水平方向
<StackPanel Orientation="Horizontal">
<RadioButton Margin="4">test1</RadioButton>
<RadioButton Margin="4">test2</RadioButton>
<RadioButton Margin="4">test3</RadioButton>
</StackPanel>
---垂直方向
<StackPanel Orientation="Vertical">
<RadioButton Margin="4">test1</RadioButton>
<RadioButton Margin="4">test2</RadioButton>
<RadioButton Margin="4">test3</RadioButton>
</StackPanel>
--レンダリング結果
---水平方向
#ref(HorizontalRenderingResultOfStackPanel.png,left,nowra...
---垂直方向
#ref(VerticalRenderingResultOfStackPanel.png,left,nowrap,...
-整列方向は、StackPanel.Orientationプロパティ(Orientatio...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***折り返しパネル [#c1367ccd]
-子要素を水平方向または垂直方向に整列し、端に達したら改行...
※ パネルのサイズが変更されると、改行位置も変更される。
--XAML
---水平方向
<WrapPanel Orientation="Horizontal">
<Button Width="26" Height="26" Margin="4" Content="0">...
<Button Width="26" Height="26" Margin="4" Content="1">...
<Button Width="26" Height="26" Margin="4" Content="2">...
・・・
<Button Width="26" Height="26" Margin="4" Content="7">...
<Button Width="26" Height="26" Margin="4" Content="8">...
<Button Width="26" Height="26" Margin="4" Content="9">...
</WrapPanel>
---垂直方向
<WrapPanel Orientation="Vertical">
<Button Width="26" Height="26" Margin="4" Content="0">...
<Button Width="26" Height="26" Margin="4" Content="1">...
<Button Width="26" Height="26" Margin="4" Content="2">...
・・・
<Button Width="26" Height="26" Margin="4" Content="7">...
<Button Width="26" Height="26" Margin="4" Content="8">...
<Button Width="26" Height="26" Margin="4" Content="9">...
</WrapPanel>
--レンダリング結果
---水平方向
#ref(HorizontalRenderingResultOfWrapPanel.png,left,nowrap...
---垂直方向
#ref(VerticalRenderingResultOfWrapPanel.png,left,nowrap,...
-整列方向は、WrapPanel.Orientationプロパティ(Orientation...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***(均一)グリッド パネル [#h66a8f8e]
-列と行で構成されているグリッド領域を定義する。~
※ グリッド内のすべてのセルが同じサイズである必要がある。
--XAML
---3行 * 4列
<UniformGrid Rows="3" Columns="4">
<Button Width="26" Height="26" Margin="4" Content="0">...
<Button Width="26" Height="26" Margin="4" Content="1">...
<Button Width="26" Height="26" Margin="4" Content="2">...
・・・
<Button Width="26" Height="26" Margin="4" Content="7">...
<Button Width="26" Height="26" Margin="4" Content="8">...
<Button Width="26" Height="26" Margin="4" Content="9">...
</UniformGrid>
---4行 * 3列
<UniformGrid Rows="4" Columns="3">
<Button Width="26" Height="26" Margin="4" Content="0">...
<Button Width="26" Height="26" Margin="4" Content="1">...
<Button Width="26" Height="26" Margin="4" Content="2">...
・・・
<Button Width="26" Height="26" Margin="4" Content="7">...
<Button Width="26" Height="26" Margin="4" Content="8">...
<Button Width="26" Height="26" Margin="4" Content="9">...
</UniformGrid>
--レンダリング結果
---3行 * 4列
#ref(RenderingResultOfUniformGrid34.png,left,nowrap,3行 *...
---4行 * 3列
#ref(RenderingResultOfUniformGrid43.png,left,nowrap,4行 *...
-行・列数は、UniformGrid.Rows、UniformGrid.Columns属性(U...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
***グリッド パネル [#p94f8aa7]
-列と行で構成されている柔軟なグリッド領域を定義する。
--行・列の定義にGrid.RowDefinitions、Grid.ColumnDefinitio...
---「添付プロパティ」であるGrid.Row・Grid.Column属性を使...
---列長・行長の設定も、この属性で指定する。
---このためHTMLのテーブルと使い方は異なる。
--XAML ( 4行 * 3列
<Grid Width="250" Height="100">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.ColumnSpan="3" Grid.Row="0">2005 Produ...
<TextBlock Grid.Row="1" Grid.Column="0">Quarter 1</Tex...
<TextBlock Grid.Row="1" Grid.Column="1">Quarter 2</Tex...
<TextBlock Grid.Row="1" Grid.Column="2">Quarter 3</Tex...
<TextBlock Grid.Row="2" Grid.Column="0">50000</TextBlo...
<TextBlock Grid.Row="2" Grid.Column="1">100000</TextBl...
<TextBlock Grid.Row="2" Grid.Column="2">150000</TextBl...
<TextBlock Grid.ColumnSpan="3" Grid.Row="3">Total Unit...
</Grid>
--レンダリング結果
#ref(RenderingResultOfGrid43.png,left,nowrap,4行 * 3列の...
-なお、ColumnDefinitionタグのWidth属性に" n*"と指定するこ...
--XAML ( 比率を指定
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"></RowDefinition>
<RowDefinition Height="2*"></RowDefinition>
<RowDefinition Height="3*"></RowDefinition>
</Grid.RowDefinitions>
</Grid>
--レンダリング結果
#ref(RenderingResultOfGridRatio.png,left,nowrap,比率指定...
-参考
--MSDN > .NET Frameworkクラス ライブラリ > System.Windows...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
*スタイルとテンプレート [#j0c577be]
ココでは、「外観」に関する設定を行う「[[スタイル>#v30d5ab...
-参考
--MSDN > WPFの基礎 > スタイルとテンプレート : 概念~
http://msdn.microsoft.com/ja-jp/library/bb613570.aspx
---> スタイルとテンプレート~
http://msdn.microsoft.com/ja-jp/library/ms745683.aspx
---> ControlTemplateの作成による既存のコントロールの外観...
http://msdn.microsoft.com/ja-jp/library/ee230084.aspx
--MSDN > Windows Presentation Foundation > コントロール
---> コントロールのカスタマイズ > ControlTemplateの例~
http://msdn.microsoft.com/ja-jp/library/aa970773.aspx
**スタイル [#v30d5ab6]
[[WPF]] / [[Silverlight]]で外観をカスタマイズする仕組みの...
***スタイルの基本 [#x9dade50]
「スタイル」は、UI要素の「依存関係プロパティ」の一括管理...
「スタイル」は、Style型のオブジェクトであり、各UI要素(Fr...
-外観に関する値を設定する「[[プロパティ属性構文>#tb0bd2e6...
以下は、UI要素の「依存関係プロパティ」に、「外観」に関す...
--XAML
<Grid>
<Ellipse Fill="Blue" Height="80" Width="160"/>
</Grid>
--レンダリング結果
#ref(RenderingResultOfStyle1.png,left,nowrap,外観に関する...
-[[プロパティ属性構文>#tb0bd2e6]]のスタイル化
--上記を、「[[プロパティ要素構文>#s389a559]]」を使用してS...
---TargetType属性により、「スタイル」は指定の型(ここでは...
---このTargetType属性による型指定が無いと、対象のプロパテ...
--XAML
<Grid>
<Ellipse>
<Ellipse.Style>
<Style TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</Ellipse.Style>
</Ellipse>
</Grid>
--レンダリング結果
#ref(RenderingResultOfStyle2.png,left,nowrap,プロパティ属...
-スタイルを[[リソース>#p50dd8ac]]として定義
--なお、上記の「スタイル」化は、通常のプロパティ設定を冗...
--このため、通常、「スタイル」を「[[リソース>#p50dd8ac]]...
--以下は、x:Keyを明示した例である。
---XAML
<StackPanel.Resources>
<Style x:Key="EllipseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</StackPanel.Resources>
<Ellipse Style="{StaticResource EllipseStyle}"/>
<Ellipse Style="{StaticResource EllipseStyle}"/>
</StackPanel>
---レンダリング結果
#ref(RenderingResultOfStyle3.png,left,nowrap,スタイルをリ...
-ベースクラスの型にスタイルを適用~
また、派生元(ここではShape型)が同じであれば、異なる要素...
--XAML
<StackPanel>
<StackPanel.Resources>
<Style x:Key="ShapeStyle" TargetType="Shape">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</StackPanel.Resources>
<Ellipse Style="{StaticResource ShapeStyle}"/>
<Rectangle Style="{StaticResource ShapeStyle}"/>
</StackPanel>
--レンダリング結果
#ref(RenderingResultOfStyle4.png,left,nowrap,ベースクラス...
-スタイルを全体に適用する例~
x:Keyを設定しなければ、TargetType属性により、「スタイル」...
(ただし、派生元が同じだが、型の異なる全ての要素に「スタ...
--XAML
<StackPanel>
<StackPanel.Resources>
<Style TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</StackPanel.Resources>
<Ellipse/>
<Ellipse/>
</StackPanel>
--レンダリング結果
#ref(RenderingResultOfStyle5.png,left,nowrap,スタイルを全...
***スタイルの継承 [#g2818cb4]
-TargetType プロパティが同じ2つのStyleクラスを定義し、~
BasedOnプロパティに継承元となるStyleクラスを設定すること...
>「スタイル」の継承が可能である。
>(Silverlight 2のStyleクラスにはBasedOnプロパティが存在...
-スタイルの継承例
--XAML
<StackPanel>
<StackPanel.Resources>
<Style x:Key="EllipseBaseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
<Style x:Key="EllipseInheritedStyle" TargetType="Ell...
BasedOn="{StaticResource EllipseBaseStyle}">
<Setter Property="Stroke" Value="Yellow"/>
<Setter Property="StrokeThickness" Value="10"/>
</Style>
</StackPanel.Resources>
<Ellipse Style="{StaticResource EllipseBaseStyle}"/>
<Ellipse Style="{StaticResource EllipseInheritedStyle}...
</StackPanel>
--レンダリング結果
#ref(RenderingResultOfInheritedStyle.png,left,nowrap,スタ...
***外部ディクショナリ ファイル化 [#je240854]
-「ディクショナリ ファイル」を使用して、CSSファイルのよう...
「スタイル」を外部ディクショナリ ファイルに定義することも...
-以下は、「ディクショナリ ファイル」を使用する例である。
--XAML
<Window.Resources>
<ResourceDictionary Source="Dictionary1.xaml"/>
</Window.Resources>
<StackPanel>
<StackPanel.Resources>
<Style x:Key="EllipseInheritedStyle" TargetType="Ell...
BasedOn="{StaticResource EllipseBaseStyle}">
<Setter Property="Stroke" Value="Yellow"/>
<Setter Property="StrokeThickness" Value="10"/>
</Style>
</StackPanel.Resources>
<Ellipse Style="{StaticResource EllipseBaseStyle}"/>
<Ellipse Style="{StaticResource EllipseInheritedStyle}...
</StackPanel>
--XAML ( 外部ディクショナリ ファイル : Dictionary1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="EllipseBaseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</ResourceDictionary>
***実行時スタイル [#aef5f69e]
-「[[リソースの定義と参照>#wd960230]]」の
--DynamicResource参照
--ディクショナリ ファイル
>の方法を、「スタイル」でも応用可能である。
-上記の例のXAMLを以下のように書き換え、~
コード ビハインドからResourceDictionaryを切り換え~
「スタイル」(スキン)を実行時に、動的に切り換えることが...
--XAML
<StackPanel>
<Ellipse Style="{DynamicResource MyEllipseStyle}"/>
<Button Content="青" Height="23" Name="button1" Width=...
<Button Content="赤" Height="23" Name="button2" Width=...
</StackPanel>
--XAML ( 外部ディクショナリ ファイル :
---Dictionary1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="MyEllipseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Blue"/>
<Setter Property="Height" Value="80"/>
<Setter Property="Width" Value="160"/>
</Style>
</ResourceDictionary>
---Dictionary2.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xam...
<Style x:Key="MyEllipseStyle" TargetType="Ellipse">
<Setter Property="Fill" Value="Red"/>
<Setter Property="Height" Value="160"/>
<Setter Property="Width" Value="80"/>
</Style>
</ResourceDictionary>
--コード・ビハインド
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
this.LoadResourceDictionary("Dictionary1.xaml");
}
private void button1_Click(object sender, RoutedEventA...
this.LoadResourceDictionary("Dictionary1.xaml");
}
private void button2_Click(object sender, RoutedEventA...
this.LoadResourceDictionary("Dictionary2.xaml");
}
private void LoadResourceDictionary(string name) {
ResourceDictionary dictionary =
(ResourceDictionary)Application.LoadComponent(new ...
if (dictionary != null) Application.Current.Resource...
}
}
--レンダリング結果
#ref(RenderingResultOfStyleAtRuntime.png,left,nowrap,実行...
**テンプレート [#o64ea160]
[[WPF]] / [[Silverlight]]で外観をカスタマイズする仕組みの...
***テンプレートの基本 [#l20b9ab9]
-「[[コンテンツ構文>#m4c088a5]]」でも述べたように、WPFのU...
「[[プロパティ属性構文>#tb0bd2e6]]」と「[[プロパティ要素...
--「[[スタイル>#v30d5ab6]]」属性の設定だけでなく、
--[[Contentプロパティ>#gc84bde8]](または[[Itemsプロパテ...
>このため、WPFのUIコントロールはコントロールの「外観」を...
|#|コントロールのクラス型|コンテンツを設定するプロパティ|...
|1|ContentControlクラス|[[Contentプロパティ>#gc84bde8]]|C...
|2|ItemsControlクラス|[[Itemsプロパティ>#v7960713]]|Items...
-また、「テンプレート」により、
--コントロールの「外観」を宣言型マークアップでカスタマイ...
--また、「イベント ハンドラ」や「イベント トリガ」なども...
「テンプレート」を「[[スタイル>#v30d5ab6]]」化、「[[リソ...
-「テンプレート」は、コントロールの用途毎に、複数のものが...
--テンプレートを設定するのプロパティと、テンプレートの型
|#|>|テンプレートを設定するプロパティ|テンプレートのクラ...
|1|>|[[Control.Template>http://msdn.microsoft.com/ja-jp/l...
|1-1||ContentControlの(Control. )Templateプロパティ|~||...
|1-2||ItemsControlの(Control. )Templateプロパティ|~||It...
|2|>|XXXX.XXXXTemplate|[[DataTemplate>http://msdn.microso...
|2-1||[[ContentControl.ContentTemplate>http://msdn.micros...
|2-2||[[ItemsControl.ItemTemplate>http://msdn.microsoft.c...
|3|>|その他|-|>|種々のコントロールの個別領域の外観をカス...
|3-1||[[ItemsControl.ItemsPanel>https://msdn.microsoft.co...
|3-2||[[HeaderedContentControl.HeaderTemplate>https://msd...
|3-3||[[GridViewColumn.CellTemplate>https://msdn.microsof...
-ただし、「テンプレート」で作成できる「外観」は、静的なも...
***ControlTemplateとDataTemplate [#n86551dd]
-ControlTemplate
--Control自身の見た目を決定するもの。
--多くの場合TemplateBindingを使い、テンプレート親とのコン...
-DataTemplate
--Controlに割り当てられたデータの見た目を定義するもの。
--多くの場合Bindingを使い、割り当てられたデータとのバイン...
-ControlTemplateとDataTemplateの使い分け
--その1
---ControlTemplate~
カスタマイズしたいものがコントロール自身である場合にを利...
---DataTemplate~
カスタマイズしたいものが割り当てられるデータである場合に...
--その2~
状況によっては、ControlTemplate、DataTemplateの~
どちらを使っても可能なこともあるので、再利用性で考える。
---ControlTemplate~
そのカスタマイズした結果できるであろうコントロールに、別...
---DataTemplate~
そのカスタマイズした結果できるであろうコントロールに、別...
--その3
---ControlTemplate~
ContentControlをカスタマイズする場合。
---DataTemplate~
ItemsControlをカスタマイズする場合。
***「テンプレート」値を反映させる方法 [#wc88b865]
また、親コントロールに適用した、「テンプレート」の値を~
[[Contentプロパティ>#gc84bde8]](または[[Itemsプロパティ>...
プロパティ値に反映させるにめには、下記の3通りの方法を選択...
-「プレゼンター」を利用する方法
--親コントロールの[[Contentプロパティ>#gc84bde8]]の場合は...
[[Contentプロパティ>#gc84bde8]]は、任意の型の子要素を取得...
--また、ItemsControlの[[Itemsプロパティ>#v7960713]]に対応...
[[Itemsプロパティ>#v7960713]]は、任意の型の子要素を取得し...
--その他、コントロールによって、色々なテンプレート・プレ...
---テンプレート : ItemsControl.ItemsPanelプロパティのItem...
>参考 : FrameworkTemplate クラス (System.Windows)~
https://msdn.microsoft.com/ja-jp/library/system.windows.f...
---プレゼンター : ScrollContentPresenter, CellValuePresen...
>参考 : 【WPF】Presenter(?)クラスを収集と考察。 | 創造...
http://pro.art55.jp/?eid=931821
-[[TemplateBinding の「マークアップ拡張」>#hee73def]]を使...
親コントロールに適用したプロパティ値を「テンプレート」に...
<object property="{TemplateBinding TargetProperty }" .../>
-同様に、[[RelativeSource の「マークアップ拡張」>#b35e6e7...
<Binding RelativeSource="{RelativeSource TemplatedParent...
--なお、「データ バインディング」で使用する場合は、次のよ...
<object property="{Binding RelativeSource={RelativeSourc...
--RelativeSourceの例
---XAML
<StackPanel>
<TextBlock Text="{Binding RelativeSource
={RelativeSource Self}, Path=FontFamily}" />・・・(1)
<Border Background="Black" Height="5"/>
<TextBlock Text="{Binding RelativeSource
={RelativeSource AncestorType={x:Type StackPanel}},P...
<Border Background="Black" Height="5"/>
<Button Content="Hello world">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<ContentPresenter Content="{Binding RelativeSource
={RelativeSource TemplatedParent}, Path=Conten...
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
---レンダリング結果
#ref(RenderingResultOfRelativeSource.png,left,nowrap,Rela...
--説明
---(1) では、TextBlock要素自身のFontFamilyプロパティを取...
---(2) では、親要素(AncestorType 属性に指定されているSta...
---(3) では、TemplatedParent 属性により、[[テンプレート>#...
[[Contentプロパティ>#gc84bde8]]を取得し、ContentPresenter...
***参考 [#s29b90e0]
-MSDN > Windows Presentation Foundation
--> データ > データ バインディング > データ テンプレート...
http://msdn.microsoft.com/ja-jp/library/ms742521.aspx
-WPF4.5入門 - かずきのBlog@hatena
--その47 「コンテンツモデル」~
http://blog.okazuki.jp/entry/2014/08/25/164331
--その52 「コントロールテンプレート」~
http://blog.okazuki.jp/entry/2014/09/07/195335
-WPFコントロールテンプレートとデータテンプレートの違い | ...
https://tocsworld.wordpress.com/2014/09/28/wpf%E3%82%B3%E...
**テンプレートの例 [#f9a8fb1a]
***ContentControlのテンプレート(ControlTemplate)の例 [#...
-XAML
--以下は、ControlTemplateとContentPresenterを使用したCont...
<Grid>
<Button Margin="5" Width="100" Height="100" Content="...
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
--上記のContentPresenterを、「マークアップ拡張」のTemplat...
<Grid>
<Button Margin="5" Width="100" Height="100" Content="...
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<TextBlock
Text="{TemplateBinding Content}"
HorizontalAlignment="Center" VerticalAlignme...
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
--上記のTemplateBindingを、「マークアップ拡張」のRelative...
なお、RelativeSourceの場合、TargetType属性を消しても上手...
<Grid>
<Button Margin="5" Width="100" Height="100" Content="...
<Button.Template>
<ControlTemplate>
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<TextBlock
Text="{Binding Path=Content, RelativeSource=...
HorizontalAlignment="Center" VerticalAlignme...
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
-レンダリング結果
#ref(RenderingResultOfControlTemplate.png,left,nowrap,Con...
-スタイル化
--「テンプレート」は、以下のように「スタイル」に組み込む...
---XAML
<Window.Resources>
<Style x:Key="buttonTemplate" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Margin="5" Width="100" Height="100">ボタン1</...
<Button Margin="5" Width="100" Height="100">ボタン2</...
<Button Margin="5" Width="100" Height="100"
Style="{StaticResource buttonTemplate}">ボタン3</Bu...
</StackPanel>
---レンダリング結果
#ref(RenderingResultOfStyleTemplate1.png,left,nowrap,Cont...
--なお、x:Keyを設定しなければ、TargetType属性により、~
「スタイル」は指定の型(ここではButtonコントロール)、全...
---XAML
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Margin="5" Width="100" Height="100">ボタン1</...
<Button Margin="5" Width="100" Height="100">ボタン2</...
<Button Margin="5" Width="100" Height="100">ボタン3</...
</StackPanel>
---レンダリング結果
#ref(RenderingResultOfStyleTemplate2.png,left,nowrap,Cont...
-リソース化
--「テンプレート」と「スタイル」を別々の「リソース」とし...
StaticResource参照の「マークアップ拡張」により~
「テンプレート」を「スタイル」に組み込むことも可能である。
---XAML
<Window.Resources>
<ControlTemplate x:Key="buttonTemplate" TargetType="Bu...
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
<Style TargetType="Button">
<Setter Property="Template" Value="{StaticResource b...
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Margin="5" Width="100" Height="100">ボタン1</...
<Button Margin="5" Width="100" Height="100">ボタン2</...
<Button Margin="5" Width="100" Height="100">ボタン3</...
</StackPanel>
--以下、同様に、「ディクショナリ ファイル」を使用して、CS...
「テンプレート」を外部ファイルに定義することも可能である。
---XAML
<Window.Resources>
<ResourceDictionary Source="TemplateStyleDictionary.xa...
</Window.Resources>
<StackPanel Orientation="Vertical">
<Button Margin="5" Width="100" Height="100">ボタン1</...
<Button Margin="5" Width="100" Height="100">ボタン2</...
<Button Margin="5" Width="100" Height="100">ボタン3</...
</StackPanel>
---XAML ( 外部ディクショナリ ファイル : TemplateStyleDict...
<ResourceDictionary xmlns="http://schemas.microsoft.com/...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ControlTemplate x:Key="buttonTemplate" TargetType="Bu...
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
<Style TargetType="Button">
<Setter Property="Template" Value="{StaticResource b...
</Style>
</ResourceDictionary>
--レンダリング結果
#ref(RenderingResultOfStyleTemplate2.png,left,nowrap,Cont...
***ContentControlのテンプレート(DataTemplate)の例 [#i42...
-以下は、ControlTemplate + ContentPresenterとDataTemplat...
--XAML
<Grid>
<Button Content="Click Here"
Margin="5" Width="100" Height="100">
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="Blue"/>
<Ellipse Fill="Red"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
<Button.ContentTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding}"/>
</Grid>
</DataTemplate>
</Button.ContentTemplate>
</Button>
</Grid>
--レンダリング結果
#ref(RenderingResultOfDataTemplateOfContentControl.png,le...
--上記の通り、DataTemplate内でContentプロパティのデータを...
-DataTemplateのポイント
--通常、ContentControl内にはContentControl.Contentプロパ...
ControlTemplateだけで事足りることが多く、DataTemplateの利...
--なお、ControlTemplate + ContentPresenterとDataTemplate...
必ずしも併用しなくても良い(DataTemplateのみの利用も可能...
--DataTemplate内でContentプロパティ以外のデータを使用する...
<TextBlock Text="{Binding RelativeSource={RelativeSource...
>>などの記述方法がある。
***ItemsControlのテンプレート(DataTemplate)の例 [#p680d...
-以下は、ItemsControl.ItemTemplateプロパティを使用したLis...
--これは、前述のサンプルの改良版である。
---[[Itemsプロパティ>#v7960713]]
---[[データ バインディングの基礎>#h0ae3316]]
--基本的に、~
ItemsControlコントロールに「データ バインディング」を行っ...
ItemsControl.ItemTemplateプロパティへ、DataTemplateを指定...
--コード
---XAML
<Grid>
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="ListBox1" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush ="Black" BorderThickness =...
<StackPanel Orientation="Horizontal" Height=...
<Image Height="100" Source="{Binding Path=...
<TextBlock Text="{Binding Path=[Text]}" V...
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
---コード ビハインド
public Window1() {
InitializeComponent();
List<Dictionary<string, string>> lst
= new List<Dictionary<string, string>>();
Dictionary<string, string> dic = null;
dic = new Dictionary<string, string>();
dic["Image"] = @".\Blue hills.jpg";
dic["Text"] = "Blue hills";
lst.Add(dic);
dic = new Dictionary<string, string>();
dic["Image"] = @".\Sunset.jpg";
dic["Text"] = "Sunset";
lst.Add(dic);
dic = new Dictionary<string, string>();
dic["Image"] = @".\Water lilies.jpg";
dic["Text"] = "Water lilies";
lst.Add(dic);
dic = new Dictionary<string, string>();
dic["Image"] = @".\Winter.jpg";
dic["Text"] = "Winter";
lst.Add(dic);
this.stackPanel1.DataContext = lst;
}
---補足~
補足となるが、選択したオブジェクトは、以下のコードで取得...
Dictionary<string, string> dic = (Dictionary<string, str...
-なお、「バインディング ソース」にDataTableを使用する場合...
--DataTableのDataColumnのColumnNameプロパティをPath属性に...
「通常のプロパティの場合の記述方法」・「インデクサの場合...
--また、ここでは、「テンプレート」を「リソース」として定...
--コード
---XAML
<Window.Resources>
<DataTemplate x:Key="listBoxStyle">
<Border BorderBrush ="Black" BorderThickness ="1" Ma...
<StackPanel Orientation="Horizontal" Height="120" ...
<Image Height="100" Source="{Binding Path=Image}...
<TextBlock Text="{Binding Path=[Text]}" Vertica...
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="ListBox1"
ItemsSource="{Binding}" ItemTemplate="{StaticResou...
</StackPanel>
</Grid>
---コード ビハインド
public Window1() {
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Image"));
dt.Columns.Add(new DataColumn("Text"));
DataRow dr = null;
dr = dt.NewRow();
dr["Image"] = @".\Blue hills.jpg";
dr["Text"] = "Blue hills";
dt.Rows.Add(dr);
・・・
dr = dt.NewRow();
dr["Image"] = @".\Winter.jpg";
dr["Text"] = "Winter";
dt.Rows.Add(dr);
this.stackPanel1.DataContext = dt;
}
---補足~
補足となるが、選択したオブジェクトは、以下のコードで取得...
DataRow dr = (DataRow)this.ListBox1.SelectedValue;
-レンダリング結果
#ref(RenderingResultOfDataTemplateOfItemsControl.png,left...
***ItemsControl(DisplayMemberPath, SelectedValuePath)の...
-ここまで、ItemsControl.ItemTemplateプロパティへ、DataTem...
代表的なItemsControlコントロールであるListBoxやComboBox(...
DisplayMemberPath、SelectedValuePathなどの属性を持ってい...
-このため、単純な表示であればItemsControl.ItemTemplateプ...
「データ バインディング」したオブジェクトから「表示項目」...
-以下、その例を示す。
--XAML
<Grid>
<StackPanel x:Name="stackPanel1">
<ListBox x:Name="ListBox1" ItemsSource="{Binding}"
SelectedValuePath="Value" DisplayMemberPath="Displ...
<Button Click="Button_Click">選択値</Button>
</StackPanel>
</Grid>
--コード ビハインド
public Window1() {
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Value"));
dt.Columns.Add(new DataColumn("Display"));
DataRow dr = null;
dr = dt.NewRow();
dr["Value"] = "0001";
dr["Display"] = "0001の表示";
dt.Rows.Add(dr);
・・・
dr = dt.NewRow();
dr["Value"] = "0004";
dr["Display"] = "0004の表示";
dt.Rows.Add(dr);
this.stackPanel1.DataContext = dt;
}
--レンダリング結果
#ref(RenderingResultOfListBox1.png,left,nowrap,SelectedVa...
-DisplayMemberPath属性に指定されたデータが表示項目となり、~
SelectedValuePath属性に指定されたデータがSelectedValueプ...
以下は、選択されたデータを取得するコードの例である。
--コード ビハインド
private void Button_Click(object sender, RoutedEventArgs...
MessageBox.Show(this.ListBox1.SelectedValue.ToString());
}
--選択されたデータ
#ref(RenderingResultOfListBox2.png,left,nowrap,SelectedVa...
***その他のItemsControlのテンプレートの例 [#eb36bade]
-ControlTemplateを使用したItemsControl
--以下は、ControlTemplateを使用したItemsControl(ListBox...
--通常、ItemsControlではDataTemplateだけで事足りることが...
ここではControlTemplate内でItemsPresenterを使用してItems...
--XAML
<Grid>
<ListBox>
<ListBox.Template>
<ControlTemplate>
<ItemsPresenter Margin="5" HorizontalAlignment="...
</ControlTemplate>
</ListBox.Template>
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
</ListBox>
</Grid>
--レンダリング結果
#ref(RenderingResultOfControlTemplateOfItemsControl.png,l...
-ItemsPanelTemplateを使用したItemsControl
--Itemsプロパティのデータの並び(レイアウト)は、~
ItemsControl.ItemsPanel プロパティにItemsPanelTemplate を...
--ここではStackPanelを使用し、各アイテムの並びを横並びに...
--XAML
<Grid>
<ListBox>
<ListBox.Template>
<ControlTemplate TargetType="ListBox">
<ItemsPresenter Margin="5" HorizontalAlignment="...
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
</ListBox>
</Grid>
--レンダリング結果
#ref(RenderingResultOfItemsPanelTemplate.png,left,nowrap,...
--参考
---MSDN > .NET Frameworkクラス ライブラリ~
● System.Windows.Controls.ItemsControl.ItemsPanelプロパテ...
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
● System.Windows.Controls.ItemsPanelTemplateクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.co...
-ヘッダの追加(ControlTemplate)
--ItemsControlでは、ControlTemplateは(繰り返し項目以外の...
--以下、ヘッダをControlTemplateで実装し、データをDataTemp...
--コード
---XAML
<Grid>
<ListBox Name="listBox1" ItemsSource="{Binding}">
<ListBox.Template>
<ControlTemplate>
<StackPanel>
<StackPanel Orientation="Horizontal" Backgrou...
<TextBlock Width="100" Text="ヘッダ1"/>
<TextBlock Width="100" Text="ヘッダ2"/>
</StackPanel>
<ItemsPresenter/> ・・・ItemsPresenterを忘れな...
</StackPanel>
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Width="100" Text="{Binding Path=[da...
<TextBlock Width="100" Text="{Binding Path=[da...
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
---コード ビハインド
public Window1() {
InitializeComponent();
List<Dictionary<string, string>> lst = new List<Dictio...
Dictionary<string, string> dic = null;
dic = new Dictionary<string, string>();
dic["data1"] = "データ11";
dic["data2"] = "データ11";
lst.Add(dic);
dic = new Dictionary<string, string>();
dic["data1"] = "データ21";
dic["data2"] = "データ22";
lst.Add(dic);
this.listBox1.DataContext = lst;
}
--レンダリング結果
#ref(RenderingResultOfControlTemplateOfItemsControlWithHe...
--グリッド系のコントロールには、ヘッダ専用の「テンプレー...
-各種テンプレートの組み合わせ~
以下は、DataTemplate、ControlTemplate、ItemsPanelTemplate...
[[ItemsControlのテンプレート(DataTemplate)の例>#p680d34...
ItemsControl(ListBox)コントロールの例である(中央揃え+...
--コード
---XAML
<Grid>
<StackPanel x:Name="stackPanel1">
<Button x:Name="button1" Click="button1_Click">選択<...
<ListBox x:Name="ListBox1" ItemsSource="{Binding}">
<ListBox.Template>
<ControlTemplate>
<ItemsPresenter Margin="5" HorizontalAlignment...
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush ="Black" BorderThickness =...
<StackPanel Orientation="Horizontal" Height=...
<Image Height="100" Source="{Binding Path=...
<TextBlock Text="{Binding Path=[Text]}" V...
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
---コード ビハインド
public Window1() {
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Image"));
dt.Columns.Add(new DataColumn("Text"));
DataRow dr = null;
dr = dt.NewRow();
dr["Image"] = @".\Blue hills.jpg";
dr["Text"] = "Blue hills";
dt.Rows.Add(dr);
・・・
dr = dt.NewRow();
dr["Image"] = @".\Winter.jpg";
dr["Text"] = "Winter";
dt.Rows.Add(dr);
this.stackPanel1.DataContext = dt;
}
private void Button_Click(object sender, RoutedEventArgs...
MessageBox.Show(this.ListBox1.SelectedValue.ToString());
}
--レンダリング結果
#ref(RenderingResultOfVariousTemplatesOfItemsControl.png,...
***グリッド系コントロールの例 [#dcea1bb1]
-ヘッダ・セルのカスタマイズ~
以下、ListViewコントロールのヘッダとセルのカスタマイズの...
--コード
---XAML
<Window.Resources>
<Style x:Key="listViewItemStyle" TargetType="ListViewI...
<Setter Property="BorderBrush" Value="Gray"/>
<Setter Property="BorderThickness" Value="2"/>
</Style>
<DataTemplate x:Key="listViewHeaderTemplate">
<TextBlock FontSize="16" Foreground="Navy" Text="{Bi...
</DataTemplate>
<DataTemplate x:Key="listViewCellStyle">
<Border BorderBrush ="Black" BorderThickness ="5" Ma...
<Image Height="100" Source="{Binding Path=Image}" />
</Border>
</DataTemplate>
</Window.Resources>
<StackPanel x:Name="stackPanel1">
<ListView x:Name="listView1" ItemsSource="{Binding}"
ItemContainerStyle="{StaticResource listViewItemStyl...
<ListView.View>
<GridView ColumnHeaderTemplate="{StaticResource li...
<GridViewColumn Header="名称"
DisplayMemberBinding="{Binding Path=Text}" />
<GridViewColumn Header="画像"
CellTemplate="{StaticResource listViewCellStyl...
</GridView>
</ListView.View>
</ListView>
</StackPanel>
---コード ビハインド
public Window1() {
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Image"));
dt.Columns.Add(new DataColumn("Text"));
DataRow dr = null;
dr = dt.NewRow();
dr["Image"] = @".\Blue hills.jpg";
dr["Text"] = "Blue hills";
dt.Rows.Add(dr);
・・・
this.stackPanel1.DataContext = dt;
}
--レンダリング結果
#ref(RenderingResultOfGridControlWithHeader.png,left,nowr...
--グリッド系のコントロール(ListView・GridView)は、以下...
---GridViewColumn クラスを使用した列の定義、
---GridViewColumn.CellTemplate プロパティへの列「テンプレ...
---GridView.ColumnHeaderTemplate プロパティへのヘッダ「テ...
-セルにComboBoxを入れる
--ListViewコントロールのセルにComboBoxを入れることも可能...
この場合、列「テンプレート」を定義して、GridViewColumn.Ce...
--この際、「データ バインディング」を使用してComboBoxを初...
StaticResourceを使用した「データ バインディング」にて行う...
このため、ComboBoxボックス毎に「リソース」に定義するクラ...
--この処理を実装する際のポイントは、以下のとおりである。
---ComboBoxボックス毎に「リソース」に定義するクラス型を作...
基本クラスなどを用いて、このクラス型の定義を簡単に行える...
---上記で作成したComboBoxボックス毎に「リソース」に定義す...
各クラスのコンストラクタに実装する必要があるが、3層C/S型...
ラウンドトリップが多くなってしまうことがあるため、集約し...
--サンプル~
https://github.com/OpenTouryoProject/SampleProgram/tree/m...
*トリガ [#x73e9a3a]
-トリガは、
--Style 、ControlTemplate 、DataTemplate などの、~
UIElementの視覚化を指定するオブジェクトのプロパティとして...
--「ある事象」をきっかけにして、そのUIElementの視覚設定を...
>ものである。
-トリガには、以下の3種類が存在し、それぞれ、きっかけとな...
--プロパティ トリガ~
きっかけ:上記の適用されているUIElementのプロパティの変更
--データ トリガ~
きっかけ:UIElementにバインドされたデータのプロパティの変更
--イベント トリガ~
きっかけ:上記の適用されているUIElementでハンドルできる「...
-以下、それぞれのトリガについて説明する。
**プロパティ トリガ [#z60358ba]
-プロパティ トリガは、UIElementのプロパティ値に基づく。
-データトリガには、Triggerと、MultiTriggerの2つがある。
-以下は、プロパティ トリガとStyleを組み合わせて利用した例...
--XAML
<Window.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button...
<Setter Property="Background" Value="LightYellow" />
<!--IsPressed = True で、背景色変更-->
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="LightBlue" />
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="ButtonStyle2" TargetType="{x:Type Button...
<Setter Property="Background" Value="LightYellow" />
<!--IsMouseOver = True で、背景色変更-->
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="LightBlue" />
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="ButtonStyle3" TargetType="{x:Type Button...
<Setter Property="Background" Value="LightYellow" />
<!--IsMouseOver、IsFocused = True で、背景色変更-->
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
<Condition Property="IsFocused" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="Background" Value="LightBlue" />
</MultiTrigger >
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Style="{StaticResource ButtonStyle1}" Grid.Row...
<Button Style="{StaticResource ButtonStyle2}" Grid.Row...
<Button Style="{StaticResource ButtonStyle3}" Grid.Row...
</Grid>
--レンダリング結果
#ref(RenderingResultOfPropertyTrigger.png,left,nowrap,プ...
-参考
--MSDN > .NET Frameworkクラス ライブラリ
---> System.Windows.Triggerクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.tr...
---> System.Windows.MultiTriggerクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.mu...
**データ トリガ [#af3def31]
-データ トリガは、UIElementのプロパティ値ではなく、~
バインドされたデータのプロパティ値に基づく。
-データトリガには、DataTriggerと、MultiDataTriggerの2つが...
-以下は、データ トリガとStyleを組み合わせて利用した例であ...
--コード
---XAML
<Window.Resources>
<my:Places x:Key="PlacesData"/>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<!--DataTrigger(Condition×1)-->
<!-- State = WA の行は文字色 = 赤-->
<DataTrigger Binding="{Binding Path=State}" Value=...
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
<!--MultiDataTrigger(Condition×n)-->
<!-- Name = Portland, State = OR の行は背景色 = 黄...
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Name}" Value...
<Condition Binding="{Binding Path=State}" Valu...
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Yellow" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
<DataTemplate DataType="{x:Type my:Place}">
<StackPanel Orientation="Horizontal" HorizontalAlign...
<TextBlock Width="20"/>
<TextBlock Width="100" Text="{Binding Path=Name}"/>
<TextBlock Width="20"/>
<TextBlock Text="{Binding Path=State}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<TextBlock Margin="5" HorizontalAlignment="Center">Dat...
<ListBox HorizontalAlignment="Stretch"
ItemsSource="{Binding Source={StaticResource ...
</StackPanel>
---コード ビハインド~
カスタムクラスであるPlaces(前述のXAMLのWindow.Resources...
(StaticResourceから)直接初期化できるように以下のように...
/// <summary>Place</summary>
public class Place {
/// <summary>名前</summary>
private string _name;
/// <summary>状態</summary>
private string _state;
/// <summary>名前</summary>
public string Name {
get { return _name; }
set { _name = value; }
}
/// <summary>状態</summary>
public string State {
get { return _state; }
set { _state = value; }
}
/// <summary>コンストラクタ</summary>
public Place(string name, string state) {
this._name = name;
this._state = state;
}
}
public class Places : ObservableCollection<Place> {
/// <summary>コンストラクタで</summary>
public Places() {
this.Add(new Place("Bellevue", "WA"));
this.Add(new Place("Gold Beach", "OR"));
this.Add(new Place("Kirkland", "WA"));
this.Add(new Place("Los Angeles", "CA"));
this.Add(new Place("Portland", "ME"));
this.Add(new Place("Portland", "OR"));
this.Add(new Place("Redmond", "WA"));
this.Add(new Place("San Diego", "CA"));
this.Add(new Place("San Francisco", "CA"));
this.Add(new Place("San Jose", "CA"));
this.Add(new Place("Seattle", "WA"));
}
}
--レンダリング結果
#ref(RenderingResultOfDataTrigger.png,left,nowrap,データ ...
-参考
--MSDN > .NET Frameworkクラス ライブラリ
---> System.Windows.DataTriggerクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.da...
---> System.Windows.MultiDataTriggerクラス~
http://msdn.microsoft.com/ja-jp/library/system.windows.mu...
**イベント トリガ [#p908262c]
-通常、イベント トリガはアニメーション処理開始の指定のた...
-これについては、「[[アニメーション>XAMLの書き方(2)#x6...
-なお、イベント トリガはFrameworkElementにも指定すること...
-参考
--MSDN > .NET Frameworkクラス ライブラリ
---> System.Windows.FrameworkElement.Triggersプロパティ~
http://msdn.microsoft.com/ja-jp/library/system.windows.fr...
----
Tags: [[:.NET開発]], [[:UIサブシステム]], [[:WPF/Silverli...
ページ名: