WPF Listbox

WPF Listboxのサンプル。


1,簡単な例
public MainWindow()
{
InitializeComponent();

Do1();
//Do2();
//Do3();
//Do4();
//Do5();
}

void Do1()
{
string [] nms = {"1", "2", "3" };
listBox1.ItemsSource = nms;
}

XAML---------------


                                                                                                                                      • -

2,DataTemplateはContentPresenterの内部を決める、簡易なテンプレート

void Do2()
{
List ls = new List();

Book bk = new Book(); bk.cd="0001"; bk.nm = "test1"; ls.Add(bk);
bk = new Book(); bk.cd="0002"; bk.nm = "test2"; ls.Add(bk);
bk = new Book(); bk.cd="0003"; bk.nm = "test3"; ls.Add(bk);

listBox1.ItemsSource = ls;
}

XAML---------------











                                                                                                                                      • -

3,ControlTemplateはContentPresenterより上位の操作をするための高度なテンプレート
class Book
{
public string cd {get;set;}
public string nm { get;set;}
}
void Do3()
{
List ls = new List();

Book bk = new Book(); bk.cd="0001"; bk.nm = "test1"; ls.Add(bk);
bk = new Book(); bk.cd="0002"; bk.nm = "test2"; ls.Add(bk);
bk = new Book(); bk.cd="0003"; bk.nm = "test3"; ls.Add(bk);

listBox1.ItemsSource = ls;
}

XAML---------------

< Style x:Key="hoi3" TargetType="{x:Type ListBoxItem}">








// セレクトされたら赤になる





//セレクトされず、フォーカスがはずれたら#FFEEEEEEになる






















                                                                                                                                      • -

4,データがXMLの場合。XmlDataProviderはTwoWayで大本のデータを操作する。

void Do3()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml( "0001test10002test20003test3");


XmlDataProvider xdp = new XmlDataProvider();

xdp.Document = doc;
xdp.XPath = "root/row";
listBox1.DataContext = xdp;
}

XAML---------------












                                                                                                                                      • -

5, 4と同じだが、画面も動的作成 (FrameworkElementFactoryでテンプレート作成はよくないらしい http://msdn.microsoft.com/ja-jp/library/system.windows.frameworkelementfactory.aspx)
void Do5()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml( "0001test10002test20003test3");


System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter sw = new System.IO.StreamWriter( ms );
sw.Write( "");

sw.Write( "" );
sw.Write( "" );
sw.Write( "" );
sw.Write( "
" );
sw.Write( "" );

sw.Flush();
ms.Position = 0;

listBox1.ItemTemplate = (DataTemplate)XamlReader.Load( ms );

sw.Close();

XmlDataProvider xdp = new XmlDataProvider();
xdp.Document = doc;
xdp.XPath = "root/row";
listBox1.DataContext = xdp;
}


XAML---------------



                                                                                                                                      • -

メモ
listBox1のオブジェクトのプロパティをReflection経由で取得し表示する例。