microsoft / xaml-standard

XAML Standard : a set of principles that drive XAML dialect alignment
Other
805 stars 50 forks source link

Simplify INotifyPropertyChanged implementation for simple properties #62

Open Licantrop0 opened 7 years ago

Licantrop0 commented 7 years ago

Every time I have to implement a simple property that needs notification, I need to implement INotifyPropertyChanged (or use a framework that already includes a base class like ObservableObject or ViewModelBase), and write this:

private string _name;
public string Name
{
   get { return _name; }
   set
   {
      if(_name == value)
         return;
      _name = value;
      RaisePropertyChanged();
   }
}

or, with a shorter syntax provided by many frameworks:

private string _name;
public string Name
{
   get => _name;
   set => Set(ref _name, value);
}

I would be better if we have another way to implement simple properties, like this:

[NotifyPropertyChanged]
public string Name { get; set; }
tpetrina commented 7 years ago

You can do that using IL weawing library like Fody. Other than that, this is not really part of XAML, it is more a problem of writing less code.

GeraudFabien commented 7 years ago

set { if(_name == value) return; _name = value; RaisePropertyChanged(); } set { if(_name != value){ _name = value; Notify(); } } Like @tpetrina says many framework do this with weaving. You also can do this with reflexion (But you may watch for performance for heavy set parameter). And it have nothinks to do with XAML. Maybe .Net standart or C# depend on what you asking. You may look at https://github.com/dotnet/csharplang/issues/341

skendrot commented 7 years ago

This wouldn't be part of the XAML Standard. This is best for the .NET Team

monkeynoises commented 7 years ago

Maybe the binding system could have a way to define whether "propertychangenotification" behaviour is added/wrapped around a type that doesn't already have it. Sometimes, you want to use types which were never designed to have INotifyPropertyChanged, et al....and you don't have the source. So you have to spend a lot of effort doing wrapper classes, or using AutoMapper, things like that to do it.

A new markupextension (or some attributes on Binding) could let you "turn on" the notifications. For more advanced scenarios....you could "define" a mapping table for a type....which let you specify each property you wanted to be notified about, etc.

http://www.codemag.com/Article/0907101

(they've implemented an {x:Update} markupextension to do binding in this way)

At the end of the day.....code is more adaptable and best when it is POCO, and isn't littered with model/platform specific behaviour.

http://10rem.net/blog/2010/12/17/puff-the-magic-poco-binding-and-inotifypropertychanged-in-wpf

WPF kind of had a way to provide the change notification if you didn't have INotifyPropertyChanged....but it didn't work with changes made by codebehind. Whichever way it's done, needs to be optimal in memory usage.