#region CPL License
/*
Nuclex Framework
Copyright (C) 2002-2019 Nuclex Development Labs
This library is free software; you can redistribute it and/or
modify it under the terms of the IBM Common Public License as
published by the IBM Corporation; either version 1.0 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
IBM Common Public License for more details.
You should have received a copy of the IBM Common Public
License along with this library
*/
#endregion
using System;
using System.ComponentModel;
using System.Windows.Forms;
using Nuclex.Support;
namespace Nuclex.Windows.Forms.Views {
///
/// Base class for MVVM user controls that act as views connected to a view model
///
public class ViewControl : UserControl, IView {
/// Initializes a new view control
public ViewControl() {
this.onViewModelPropertyChangedDelegate = OnViewModelPropertyChanged;
}
/// Called when the control's data context is changed
/// Control whose data context was changed
/// Data context that was previously used
/// Data context that will be used from now on
protected virtual void OnDataContextChanged(
object sender, object oldDataContext, object newDataContext
) {
var oldViewModel = oldDataContext as INotifyPropertyChanged;
if(oldViewModel != null) {
oldViewModel.PropertyChanged -= this.onViewModelPropertyChangedDelegate;
}
var newViewModel = newDataContext as INotifyPropertyChanged;
if(newViewModel != null) {
newViewModel.PropertyChanged += this.onViewModelPropertyChangedDelegate;
InvalidateAllViewModelProperties();
}
}
/// Refreshes all properties from the view model
protected void InvalidateAllViewModelProperties() {
OnViewModelPropertyChanged(this.dataContext, PropertyChangedEventArgsHelper.Wildcard);
}
/// Called when a property of the view model is changed
/// View model in which a property was changed
/// Contains the name of the property that has changed
protected virtual void OnViewModelPropertyChanged(
object sender, PropertyChangedEventArgs arguments
) { }
/// Provides the data binding target for the view
public object DataContext {
get { return this.dataContext; }
set {
if(value != this.dataContext) {
this.dataContext = value;
}
}
}
/// Active data binding target, can be null
private object dataContext;
/// Delegate for the OnViewModelPropertyChanged() method
private PropertyChangedEventHandler onViewModelPropertyChangedDelegate;
}
} // namespace Nuclex.Windows.Forms.Views