#region Apache License 2.0 /* Nuclex .NET Framework Copyright (C) 2002-2024 Markus Ewald / Nuclex Development Labs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion // Apache License 2.0 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) { object oldDataContext = this.dataContext; this.dataContext = value; OnDataContextChanged(this, oldDataContext, value); } } } /// Active data binding target, can be null private object dataContext; /// Delegate for the OnViewModelPropertyChanged() method private PropertyChangedEventHandler onViewModelPropertyChangedDelegate; } } // namespace Nuclex.Windows.Forms.Views