[10 行でズバリ!! リスト アイテムの表現 (C#)]をダウンロードする。
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:mscorlib="clr-namespace:System.Reflection;assembly=mscorlib" >
<Window.Resources>
<!-- PropertyInfo オブジェクトに適用するデータ テンプレート -->
<DataTemplate DataType="{x:Type mscorlib:PropertyInfo}">
<StackPanel Orientation="Horizontal" Margin="3">
<Border BorderBrush="Black" BorderThickness="2"
CornerRadius="5" Width="20" Height="20"
Background="{Binding Path=Name}" />
<TextBlock Margin="5,0,5,0" Text="{Binding Path=Name}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel Background="LightPink">
<TextBox Name="textBox1" Margin="5" Text="TEST"/>
<Slider Name="slider1" Margin="5" Minimum="10" Maximum="50" Value="30"/>
<ComboBox Name="comboBox1" Margin="5" Width="150"
MaxDropDownHeight="300"
Loaded="comboBox1_Loaded" />
<TextBlock Name="textBlock1" Margin="5" TextWrapping="Wrap"
Text="{Binding ElementName=textBox1, Path=Text}"
FontSize="{Binding ElementName=slider1, Path=Value}"
Foreground="{Binding ElementName=comboBox1, Path=SelectedValue.Name}" />
</StackPanel>
</Window>
</Ellipse>
</Canvas>
</Window>
<Window>階層1:クラス:
<Window.Resources>階層2-1:プロパティ:
<DataTemplate>階層3-1:クラス:
<StackPanel>階層4-1:クラス:
<Border/>階層5-1:クラス:
<TextBlock />階層5-1:クラス:
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>階層2-2:クラス:
<TextBox/>階層3-2:クラス:
<Slider/>階層3-2:クラス:
<ComboBox/>階層3-2:クラス:
<TextBlock/>階層3-2:クラス:
</StackPanel>
</Window>
(1)XAMLを理解するには、まずXAMLの階層構造を理解する必要があります。(サンプルは上記のようになります。)
using System.Windows;
using System.Windows.Media;
using System.Reflection;
namespace PropBinding
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void comboBox1_Loaded(object sender, RoutedEventArgs e)
{
// PropertyInfo オブジェクトの配列をデータ バインディング
PropertyInfo[] colorProps = typeof(Colors).GetProperties();
this.comboBox1.ItemsSource = colorProps;
// 最初は先頭の項目が選択されている状態にする
this.comboBox1.SelectedIndex = 0;
}
}
}