Create the following class for notiyfing:
public abstract class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly Dictionary<string, object> _properties = new Dictionary<string, object>();
protected T Get<T>([CallerMemberName] string name = null)
{
Debug.Assert(name != null, "name != null");
object value = null;
if (_properties.TryGetValue(name, out value))
return value == null ? default(T) : (T)value;
return default(T);
}
protected void Set<T>(T value, [CallerMemberName] string name = null)
{
Debug.Assert(name != null, "name != null");
if (Equals(value, Get<T>(name)))
return;
_properties[name] = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public void Notify<T>(Expression<Func<T>> memberExpression)
{
if (memberExpression == null)
{
throw new ArgumentNullException("memberExpression");
}
var body = memberExpression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException("Lambda must return a property.");
}
var vmExpression = body.Expression as ConstantExpression;
if (vmExpression != null)
{
LambdaExpression lambda = Expression.Lambda(vmExpression);
Delegate vmFunc = lambda.Compile();
object sender = vmFunc.DynamicInvoke();
PropertyChanged?.Invoke(sender, new PropertyChangedEventArgs(body.Member.Name));
}
}
}
Your ViewModel should look something like this.
public class ViewModel : Notifier
{
public ObservableCollection<String> Messages
{
get { return Get<ObservableCollection<String>>(); }
set
{
Set(value);
Notify(() => AreThereMessages);
}
}
public bool AreThereMessages => Messages?.Count > 0;
}
You don't need any private variables with the Notifier class above.
Getter: get { return Get<T>(); }
Setter: get { Set(value); }
Notify other property: Notify(() => OtherProperty);
Example view:
<DataGrid ItemsSource="{Binding Messages}"/>
<Button IsEnabled="{Binding AreThereMessages}"/>
The code above notifies a button if the messages collection is empty or not.
This is the easiest way I know to handle your viewmodel without additional libraries.