Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Runtime.CompilerServices;
- using System.Threading.Tasks;
- using System.Windows.Threading;
- namespace NotifyOnPropertyChangedExample
- {
- public class PretendViewModel : NotifyOnPropertyChanged
- {
- public string Name
- {
- get
- {
- return GetField<string>();
- }
- set
- {
- SetField(value);
- }
- }
- public void SomeMethod()
- {
- Task.Factory.StartNew(() =>
- {
- Name = "Status update!";
- });
- }
- }
- public class NotifyOnPropertyChanged : INotifyPropertyChanged
- {
- #region Private Fields
- private IDictionary<string, PropertyChangedEventArgs> _args;
- private IDictionary<string, object> _fields;
- #endregion
- #region Protected Methods
- protected T GetField<T>([CallerMemberName]string name = "")
- {
- return GetField(default(T), name);
- }
- protected T GetField<T>(T defaultValue, [CallerMemberName]string name = "")
- {
- var output = defaultValue;
- if (_fields != null && _fields.ContainsKey(name))
- {
- var value = _fields[name];
- try
- {
- output = (T)value;
- }
- catch
- {
- Debug.WriteLine("Failed to convert field '{0}' of type '{1}' to type '{2}'.", name, value.GetType().Name, typeof(T).Name);
- }
- }
- return output;
- }
- protected void SetField(object value, bool doNotify = true, [CallerMemberName] string property = "")
- {
- if (_fields == null)
- {
- _fields = new Dictionary<string, object>();
- }
- if (!_fields.ContainsKey(property))
- {
- _fields.Add(property, value);
- }
- else
- {
- _fields[property] = value;
- }
- if (doNotify)
- {
- OnPropertyChanged(property);
- }
- }
- #endregion
- #region Static UI Methods
- private static Dispatcher _ui;
- public static void SetUI()
- {
- if (_ui == null)
- {
- _ui = Dispatcher.CurrentDispatcher;
- }
- else
- {
- throw new Exception("Cannot set UI dispatcher more than once.");
- }
- }
- #endregion
- #region Public Events
- public event PropertyChangedEventHandler PropertyChanged;
- #endregion
- #region Public Methods
- public void OnPropertyChanged([CallerMemberName]string property = "")
- {
- PropertyChangedEventArgs args = null;
- if (_args == null)
- {
- _args = new Dictionary<string, PropertyChangedEventArgs>();
- }
- if (!_args.ContainsKey(property))
- {
- _args.Add(property, args = new PropertyChangedEventArgs(property));
- }
- else
- {
- args = _args[property];
- }
- if (PropertyChanged != null)
- {
- if (Dispatcher.CurrentDispatcher == _ui)
- {
- PropertyChanged(this, args);
- }
- else
- {
- _ui.BeginInvoke(new Action(() => PropertyChanged(this, args)));
- }
- }
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment