おおまかな製作工程
<オブジェクトコレクションをXAMLの中で作成しリストボックスにバインド、さらにテキストボックスに選択したアイテムをバインドさせる>
<MSDN資料>
方法 : XAML でデータをバインディング可能にする:http://msdn.microsoft.com/ja-jp/library/ms748857(v=vs.100)
<要点>
1.C#でclr側にオブジェクトを作る。ObservableCollection<T>を継承させるとコレクションリストとしても扱えXAMLとの親和性も向上する
2.XAMLでリソースを作成していく。下準備として xmlns:src ="clr-namespace:WpfApplication1" 等でclrと関連つける
この”src”は一意の好きな名前が付けられる。以後この単語を名前空間として参照しオブジェクトにアクセスする
3.<Window.Resource></Window.Resource>内でリソースが作成できる
4.コレクションを作成(これはXAML内で完結して書ける点に注目)
<src:StudentList x:Key="studentCollection">
<src:Student StudentName="小山" IsEnrolled="False"/>
<src:Student StudentName="小山" IsEnrolled="False"/>
5.ListBox等の選択するタイプのエレメントは選択アイテムのプロパティを拾いたい場合、IsSynchronizedWithCurrentItem プロパティを true に設定する必要があります
これがtrueになっていないとCurrentItemが変化に同期しないので忘れないように設定する事!
注意点
-オブジェクトはビルドが通ってアセンブリとして認識されるので、どこまでIDEがオブジェクトを認識しているか状況把握できていた方がよい
-ListBoxのDisplayMemberPath等は直接キーボードでキーを入力したほうがよい(プロパティ部分では表示されるパラメータが追いついていない等インテリセンス的な入力が難しい場合があるので過信は禁物)
<XAML例>
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<src:PersonList x:Key="Test">
<src:Person Name="test1" ID="12"></src:Person>
<src:Person Name="teest2" ID="13"></src:Person>
<src:Person Name="teeest3" ID="14"></src:Person>
</src:PersonList>
</Window.Resources>
<Grid>
<ListBox Height="100" HorizontalAlignment="Left" Margin="62,37,0,0" Name="listBox1" VerticalAlignment="Top" Width="61" ItemsSource="{Binding Source={StaticResource Test}}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" />
<TextBox Height="24" HorizontalAlignment="Left" Margin="193,64,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding ElementName=listBox1, Path=Items/Name}" />
</Grid>
</Window>
<CLR例>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new { X = 10 };
}
}
class Person
{
public string Name { get; set; }
public int ID { get; set; }
}
class PersonList : ObservableCollection<Person>
{
}
}
最終更新:2012年09月12日 21:43