// parts of this code is based upon the article : http://msdn.microsoft.com/de-de/magazine/dd419663.aspx#id0090051 class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// raises the PropertyChanged event with the given string parameter /// </summary> /// <param name="propertyName">name of the property, that has changed</param> protected virtual void OnPropertyChanged(string propertyName) { // just to avoid wrong Event-Calls (only in debug mode) this.VerifyPropertyName(propertyName); // call the event handler PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } /// <summary> /// raises the PropertyChanged-event, with the name of the property that is given by the lambda expression /// </summary> /// <typeparam name="Tprop">type parameter of the given property, to be ignored</typeparam> /// <param name="property">the lambda expression f.e.: "() => TestProperty"</param> protected virtual void OnPropertyChanged<Tprop>(Expression<Func<Tprop>> property) { // cast as LambdaExpression LambdaExpression lambda_exp = (LambdaExpression)property; if (lambda_exp != null) { MemberExpression member_exp = (MemberExpression)lambda_exp.Body; if (member_exp != null) { OnPropertyChanged(member_exp.Member.Name); return; } } Debug.Fail("No correct LambdaExpression provided for OnPropertyChanged."); } [Conditional("DEBUG")] [DebuggerStepThrough] public void VerifyPropertyName(string propertyName) { // Verify that the property name matches a real, // public, instance property on this object. if (TypeDescriptor.GetProperties(this)[propertyName] == null) { string msg = "Invalid property name: " + propertyName; Debug.Fail(msg); } } }
Donnerstag, 18. Juli 2013
Code Snippet: ViewModelBase
Oft benötige ich eine Implementierung der ViewModelBase-Klasse, dann muss ich diese entweder aus anderen Projekten kopieren, oder googeln. Jetzt muss ich das nicht mehr, denn ich merk sie mir einfach hier:
Abonnieren
Kommentare zum Post (Atom)
Keine Kommentare:
Kommentar veröffentlichen