Eine View soll mit einem ViewModel in einem DataTemplate genutzt werden. Das DataTemplate hat ein Binding auf das aktuelle Model einer Collection, z.B. ItemsSource von ListBox.
Wie geht das? Oder sollte man es anders machen? - Eine Collection von ViewModels mit jeweiligen Model käme mir etwas seltsam vor.
Ja du legst dir ne Liste an mit ViewModels und Bindest daran.
Hier ein Grid:
DataSource="{Binding AllCustomers}"
Im ViewModel
public ObservableCollection<CustomerViewModel> AllCustomers { get; set; }
Constructor
public AllCustomersViewModel(ICustomerRepository repo) { if (repo == null) throw new ParameterException(typeof(ICustomerRepository).ToString());
_repo = repo;
// Liste AllCustomers neu zusamensetzen AllCustomers = new ObservableCollection<CustomerViewModel>( from c in _repo.GetAll() select new CustomerViewModel(c,_repo));
}
Das CustomerViewModel Wichtig, hier mappen vom Objekt auf das ViewModel
/// <summary> /// Gets the customer entity. /// </summary> /// <value>The customer entity.</value> public Customer CustomerEntity { get { return _customerEntity; } } private Customer _customerEntity; /// <summary> /// Gets the customer ID. /// </summary> /// <value>The customer ID.</value> public int CustomerID { get { return _customerEntity.CustomerID; } }
/// <summary> /// Gets or sets the first name. /// </summary> /// <value>The first name.</value> public string FirstName { get { return _customerEntity.FirstName; } set { if (_customerEntity.FirstName != value) { _customerEntity.FirstName = value; RaisePropertyChanged("FirstName"); } } }
mit den coolen kleinen Bildchen über der Textbox für die Antwort kann man seinen Text prima formatieren, unter anderem code in codetags packen, ich hab das mal für dich erledigt ;)