Mam kolejny problem z aplikacją WPF. Nie pisałem za wiele w WPF MVVM, więc wybaczcie moją wzmożoną aktywność :)
W modelu widoku mam zaimplementowany interfejs INotifyPropertyChanged:
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(params string[] props)
{
if (PropertyChanged != null)
{
foreach (string prop in props)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
W modelu widoku jest też instancja kolekcji obiektów, które są w nim dodane:
public static ObservableCollection<Booking> BookingList { get; set; } = new ObservableCollection<Booking>();
Przycisk widoku wywołuje komendę ReturnBooking:
<Button Grid.Row="1"
Grid.Column="9"
Style="{StaticResource buttonStyle}"
Command="{Binding Path=ReturnBooking}"
CommandParameter="{Binding ElementName=lbBookingList, Path=SelectedIndex}"
ToolTip="Marks selected booking as returned" Margin="4.667,20,5.333,10">
<TextBlock Text="Return selected booking" TextWrapping="Wrap" TextAlignment="Center"/>
</Button>
Komenda wygląda następująco:
private ICommand returnBooking;
public ICommand ReturnBooking
{
get
{
if (returnBooking == null)
returnBooking = new RelayCommand(
o =>
{
int bookingIndex = (int)o;
Booking booking = BookingList[bookingIndex];
if (booking.ReturnDate == null)
{
booking.ReturnDate = DateTime.Now;
repository.ReturnBooking(booking);
OnPropertyChanged("ReturnDate");
dialogBox.ShowDialog("Return updated", "Message");
}
else
{
dialogBox.ShowDialog("This book is already returned", "Message");
}
},
o =>
{
if (o == null) return false;
int bookingIndex = (int)o;
return bookingIndex >= 0;
});
return returnBooking;
}
}
Komenda się odnosi do właściwości ReturnDate w modelu widoku:
public DateTime? ReturnDate
{
get
{
return model.ReturnDate;
}
set
{
model.ReturnDate = value;
OnPropertyChanged("ReturnDate");
}
}
W modelu widoku znajduje się też instancja modelu:
private Booking model = new Booking();
A sam model wygląda następująco:
public class Booking
{
public int Id { get; set; }
public string Comments { get; set; }
public DateTime BorrowDate { get; set; }
public DateTime? ReturnDate { get; set; }
[ForeignKey("Reader")]
public int Reader_Id { get; set; }
public Reader Reader { get; set; }
[ForeignKey("Book")]
public int Book_Id { get; set; }
public Book Book { get; set; }
}
Nie rozumiem dlaczego po wywołaniu ICommand przez widok, w szczególności po przypisaniu ReturnDate = DateTime.Now; widok nie aktualizuje automatycznie daty? Jedynie następuje aktualizacja w DB. Czy to ma związek z faktem, że pracujemy na własności obiektu w ObservableCOllection? Czy w niewłaściwy sposób używam OnPropertyChanged("ReturnDate");?