ざっくりまとめるとこんな感じです。
まず、バインディング用のデータを保持するモデルを定義します。
public sealed class MyListBoxItem
{
public string Field1 {get;set;}
public string Field2 {get;set;}
public string Field3 {get;set;}
}
ここで、バインディングのためにこれらのモデルを保持するクラスが必要です。この型は、多くの場合、ViewModel と呼ばれます。ビューからのユーザー入力に基づいてバインドするためにビューに情報を提示します。そのパブリック プロパティは通常、ObservableCollections と DependencyProperties であるため、ViewModel の変更はビュー (UI) によって自動的に取得されます。
public sealed class MyViewModel
{
public ObservableCollection<MylistBoxItem> Items {get;private set;}
public MyViewModel()
{
Items = new ObservableCollection<MyListBoxItem>();
Items.Add(new MyListBoxItem{Field1="One", Field2="Two",Filed3="Three"};
}
}
UI のコード ビハインド (「ビュー」) 内で、ViewModel をインスタンス化し、それをビューの DataContext として設定します。
public MyView()
{
this.DataContext = new MyViewModel();
}
これは、DataContext がビジュアル ツリーを "流れる" ため重要です。それが設定されているすべての子要素で使用できます。
アイテムを表示するには、ListView の ItemsSource を DataContext の Items プロパティにバインドする必要があります (これは理解済みです)。ListView 内の各行には、Items プロパティの個々の MyViewModel に設定された DataContext があります。したがって、各表示メンバーを MyListBoxItem のプロパティにバインドする必要があります。
<ListView Name="RecordListView" ItemsSource="{Binding Items}">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="1" Width="Auto" DisplayMemberBinding="{Binding Path=Field1}" />
<GridViewColumn Header="2" Width="50" DisplayMemberBinding="{Binding Path=Field2}" />
<GridViewColumn Header="3" Width="100" DisplayMemberBinding="{Binding Path=Field3}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
このプロセス全体をよりよく理解するには、ここで[MVVM]のタグが付いた評価の高い質問を検索してください。
また、バインディングのデバッグを支援するために、詳細なデータ バインディングのデバッグを構成します。
