Reputation: 33
I am new to C# programming. I am building some classes and finding different samples in tutorials. I also believe that in order to keep a WPF form displaying the correct values you need to impliment INotify.
So my question is two parts I guess. Do I really need I notify and a custom method that fires when a property changes?
Is this the best systax to define my class?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
namespace LakesideQTS
{
public class Machine : BaseModel, IDataErrorInfo
{
private int _MachineID;
private string _Description;
public int MachineID
{
get { return _MachineID; }
set { _MachineID = value; OnPropertyChanged1("MachineID"); }
}
public string Description
{
get { return _Description; }
set { _Description = value; OnPropertyChanged1("Description"); }
}
}
}
It seems like alot of typing and really long and messy. Is there a way to call the OnPropertyChanged1() with the newer syntax style? Something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
namespace LakesideQTS
{
public class Machine : BaseModel, IDataErrorInfo
{
public int MachineID {get;set; OnPropertyChanged1("MachineID");}
public string Description {get;set; OnPropertyChanged1("MachineID");)}
}
}
Thanks for any help you guys and gals can provide!
Upvotes: 1
Views: 108
Reputation: 11754
The main reason to implement INotifyPropertyChanged (probably through your BaseModel class) is for objects where you will use GUI bounded on your model object properties. This way GUI controls will update itself when your model object property change.
The best way I have found the do a property with backing field and Notification with INotifyPropertyChanged was to use Resharper (where you will also have a lots of other useful advantages) and follow Nico receipt. You will save a lots of time and effort of repetitive job if you follow that. It require some time to setup, but you will save a lots more after. Good luck!
Upvotes: 1
Reputation: 449
There is no way to write less code to implement it.
To save some time and avoid hand-written code you can use the propfull snippet in Visual Studio.
The usage is: type propfull and press TAB 2 times.
Upvotes: 1
Reputation: 391306
No, there is no way.
You either have a barebones property like this:
public int MachineID { get; set; }
or you have the full fledged property with an explicit backing field:
private int _MachineID;
public int MachineID
{
get { return _MachineID; }
set
{
_MachineID = value;
OnNotifyPropertyChanged("MachineID");
}
}
Only the latter syntax will allow you to do anything more than just storing the value.
Upvotes: 5