WPF の ListBox のデータバインディングの設定
で、ちょっと迷ったのでメモ。
[XAML]
ItemsSource="{Binding Path=Rows}"
DisplayMemberPath="Text"
SelectedItem="{Binding Path=Row}"/>
[ViewModel]
public class HogeViewModel : INotifyPropertyChanged
{
protected virtual void OnPropertyChanged(string propertyName) {
if (this.PropertyChanged == null) return;
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private Item _Row;
public Item Row {
get { return this._Row; }
set {
if (this._Row == value) return;
this._Row = value;
this.OnPropertyChanged("Row");
}
}
private Item[] _Rows;
public Item[] Rows {
get { return this._Rows; }
set {
if (this._Rows == value) return;
this._Rows = value;
this.OnPropertyChanged("Rows");
}
}
}
[DataModel]
public class Item {
private const int CODE_MAX_LENGTH = 8;
public int Code { get; set; }
public string Name { get; set; }
public string Text { get { return this.ToString(); } }
public override string ToString() {
return this.Code.ToString().PadLeft(CODE_MAX_LENGTH, ' ') + " : " + this.Title;
}
}
ItemsSource プロパティは、コレクションオブジェクトを
DisplayMemberPath プロパティは、コレクションオブジェクトの要素の内容を表現する文字列を
SelectedItem プロパティは、現在選択中の要素のオブジェクトを格納するためのオブジェクトを指定。
急いでまとめたので、コードの記述ミスがあったら指摘してください~