Scenario
I get a model class from an external component or a code part where I do not want to alter something.
I'd like to bind this class to some WPF UI.
I also would like to refresh the UI if this model gets altered.
Question
Do I really need to write a wrapper class all the time, that creates PropertyChanged events for each setter?
How could I prevent to write all this clue coding manually?
What started like this ...
public class User : IUser
{
public String Name { get; set; }
public bool CurrentlyLoggedIn { get; set; }
// ...
}
... will always be bloated like so
public class UserObservableWrapper : IUser, INotifyPropertyChanged
{
public String Name
{
get
{
return this.innerUser.Name;
}
set
{
if (value == this.innerUser.Name)
{
return;
}
this.innerUser.Name = value;
this.OnPropertyChanged( "Name" );
}
}
public bool CurrentlyLoggedIn
{
get
{
return innerUser.CurrentlyLoggedIn;
}
set
{
if (value.Equals( innerUser.CurrentlyLoggedIn ))
{
return;
}
innerUser.CurrentlyLoggedIn = value;
this.OnPropertyChanged( "CurrentlyLoggedIn" );
}
}
private readonly IUser innerUser;
public UserObservableWrapper( IUser nonObservableUser )
{
this.innerUser = nonObservableUser;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged( string propertyName )
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler( this, new PropertyChangedEventArgs( propertyName ) );
}
}
}
There must be a more intelligent way of doing that!?
If it doesn't happen a lot of times in your code I would recommend you to do the boilerplate code.
Otherwise, you can use this cool piece of code from Ayende to generate a proxy class that would auto implement INotifyPropertyChanged for you (including event raising).
Usage would look like this:
IUser userProxy = DataBindingFactory.Create<User>();
Related
In my sample, I had used property changed event. in this handler, I had an declare a method. each and every time that method fire when changing the property,
in That method, I had set the value to the property. when I set the value, it is a call to the event handler. so it's executing the circular. how to make the method call only one time?
private string name;
public string Name
{
get { return name; }
set
{
name= value;
Name.PropertyChanged+=(s,e)=>
{
Changed(s as string);
};
}
}
private void changed(string name)
{
Name = name;
}
in this code, the changed property call every time.
The basic thing is nameof keyword:
changed(nameof(Name));
You can go futher and omit the need of specifying name at all by adding the following CallerMemberName attribute to your method's parameter:
private void changed([CallerMemberName]string name=null){}
In this case you can call this method without property name: changed();
I'd hazard a guess you want to implement MVVM. The most elegant way to implement it so far is to have the following base class:
public abstract class Observable : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetPropertyAndNotifyIfNeeded<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
NotifyPropertyChanged(propertyName);
return true;
}
protected void NotifyPropertyChanged([CallerMemberName]string name=null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
Implementation of your MVVM:
class Class1:Observable
{
public Class1()
{
}
string propertyValue;
public string Property
{
get => propertyValue;
set => SetPropertyAndNotifyIfNeeded(ref propertyValue, value);
}
}
As per your code remove subscription from your property to avoid recursive loop:
Name.PropertyChanged+=(s,e)=>
In your property call changed(nameof(Name));
class a:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
....
private string name;
public string Name
{
get { return name; }
set
{
if (name!=value)
{
name= value;
changed();
}
}
}
private void changed([CallerMemberName]string name=null)
{
PropertyChanged.?Invoke(this, new PropertyChangedEventArgs(name));
}
...
}
As I can see from your question, and I would guess, you would like to raise a Property Changed on it and set a value. Basically implement MVVM.
A really simple and quick way, would be to use a already existing Nuget package, which would simplify your job.
One that you can use is GalaSoft.MvvmLight.
After you add the Nuget package, you can just use it in the following way:
public string name;
public string Name
{
get { return name; }
set
{
name= value;
RaisePropertyChanged(nameof(Name));
}
}
RaisePropertyChanged, is going to Raise the PropertyChanged event for you (as the name itself suggests).
In C#, I have a suffiently complex Model. I already have a WPF Client to manipulate that model. I'm using MVVM. All objects in that model support INotifyPropertyChanged and all properties that are collections support INotifyCollectionChanged.
Take this as a simplied example:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace CollectionTest1
{
public class PropertyChangedSupport : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void FirePropertyChange([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Company : PropertyChangedSupport
{
private string name;
public String Name { get { return name; } set { name = value; FirePropertyChange(); } }
public ObservableCollection<Employee> Employees { get; } = new ObservableCollection<Employee>();
}
public class Employee : PropertyChangedSupport
{
private string name;
public String Name { get { return name; } set { name = value; FirePropertyChange(); } }
public ObservableCollection<PresentTimespan> PresentTimespans { get; } = new ObservableCollection<PresentTimespan>();
public Boolean IsPresentAt(DateTime t)
{
foreach (PresentTimespan pt in PresentTimespans)
{
if (pt.Start.CompareTo(t) <= 0 && pt.Finish.CompareTo(t) >= 0) return true;
}
return false;
}
}
public class PresentTimespan : PropertyChangedSupport
{
private string comment;
public String Comment { get { return comment; } set { comment = value; FirePropertyChange(); } }
private DateTime start;
public DateTime Start { get { return start; } set { start = value; FirePropertyChange(); } }
private DateTime finish;
public DateTime Finish { get { return finish; } set { finish = value; FirePropertyChange(); } }
}
public class CompanyStatusView : PropertyChangedSupport
{
private DateTime currentTime;
public DateTime CurrentTime { get { return currentTime; } set { currentTime = value; FirePropertyChange(); } }
private Company currentCompany;
public Company CurrentCompany { get { return currentCompany; } set { currentCompany = value; FirePropertyChange(); } }
public ObservableCollection<Employee> PresentEmployees { get; } = new ObservableCollection<Employee>();
public CompanyStatusView()
{
UpdatePresentEmployees();
}
private void UpdatePresentEmployees()
{
PresentEmployees.Clear();
foreach (Employee e in CurrentCompany.Employees) {
if (e.IsPresentAt(currentTime)) PresentEmployees.Add(e);
}
}
}
}
I'd like to have UpdatePresentEmployees called whenever there are changes in:
Collection Company.Employees.PresentTimespans
Property Company.Employees.PresentTimespans.Start
Property Company.Employees.PresentTimespans.Finish
Collection Company.Employees
Property CurrentTime
Property CurrentCompany
So it's basically any property or collection read by UpdatePresentEmployees.
My best solution so far included registering a lot of event handlers to all the objects mentioned above. That included to have a couple of Dictionary instances to track which added objects I have to subscribe to and especially which I have to unsubscribe from.
The most difficult and annoying part was to subscribe to all the PresentTimespan objects to listen for property changes and all the PresentTimespans collections of Employee to listen for collection changes.
My guess is that there has to be a better way to do this.
After all, in JFace (Java) there is a very interesting solution that uses ObservableTracker. So there you'd only provide the code for UpdatePresentEmployees and ObservableTracker tracks which objects have been read and automatically makes you listen for changes in any of these and also correctly unsubscribes from irrelevant objects. So there are better approaches to this problem in general. What is C# offering? Can it do better than my best solution I mentioned above? Can I avoid some of the boilerplate code? Can it be done with .net provided classes or do I need some additional classes/libraries?
Thanks for your kind help and advice in advance!
You could use BindingList instead of ObservableCollection and attach to the the ListChanged Event. But keep in mind that BindingList has some disadvantages like not being very fast. For further information this could be interesting: difference between ObservableCollection and BindingList
If you dont wanna use BindingList you have to wire your items with events.
As pointed out by Nikhil Agrawal, Rx or ReactiveUI is a good framework for my purpose. So I consider that to be a solution.
Why does C# make me do this:
public class SomeClass {
public event PropertyChangedEventHandler Changed;
public void OnChanged(object sender, PropertyChangedEventArgs e)
{
if (Changed != null)
Changed(sender, e);
}
[XmlIgnore]
private string _name;
public string Name {
get { return _name; }
set
{
_name = value;
OnChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
intead of something like this:
[GeneratesChangeNotifications]
public class SomeClass {
[GeneratesChangeNotification]
public string Name { get; set; }
}
I know you can do this with PostSharp and other 3rd party libraries... but something so integral and otherwise error prone (e.g. misspelling the name in the string), I think, should be built into the language... why doesn't Microsoft do this?... is there some purist language reason why this doesn't happen. It's a common enough need.
So far here is the best that I've come up with... I've written a class called NotifyPropertyChanged... it handles the property name, the test for if it's changed or not, the update of the local variable, and the notification of the change... and the SetProperty function is generic, so one function will work with all types of properties... works pretty well.
(Also notice you can call OnPropertyChanged with several property names if you like.)
public class NotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(params string[] props)
{
foreach (var prop in props)
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
public bool SetProperty<T>(ref T oldValue, T newValue, [CallerMemberName]string prop = "")
{
if (oldValue == null && newValue == null)
return false;
if (oldValue != null && oldValue.Equals(newValue))
return false;
oldValue = newValue;
OnPropertyChanged(prop);
return true;
}
}
Then use it like this:
public class MyClass : NotifyPropertyChanged
{
public string Text { get => _text; set => SetProperty(ref _text, value); }
string _text;
}
My RaisePropertyChanged always uses the caller member name, or if needed reflects the property name passed in in an expression (ie, if I need to make one property notify for another). You cannot always guarantee that all properties can notify, and being able to notify more than one at a time is therefore useful.
In addition, with the standard model, using an event allows anyone to subscribe, which an attributed model can not.
Update the model from the view model
I have read some post about the MVVM but I not sure if understand the
way that the view model is updating the model
Currently I have two text boxes in the UI which is bound to the XAML view and call to the view model when the event was raised .
when should be the place in the view model when I updating the model?
This is the view model
class ViewModel:INotifyPropertyChanged
{
private String _url;
private String _TemplateType;
public string URL
{
get { return _url; }
set
{
if (value != _url)
{
_url= value;
OnPropertyChanged("URL");
}
}
}
public string TemplateType
{
get { return _TemplateType; }
set
{
if (value != _TemplateType)
{
_TemplateType= value;
OnPropertyChanged("URL");
}
}
}
The model
internal class DefineAddinModel
{
public string TemplateType { get; set; }
public String URL { get; set; }
}
The ViewModel usually acts as a wrapper around the Model and contains a reference to the Model which is can update either in response to commands or automatically in property setters.
UPDATE:
Here's an example of having the VM act as a wrapper around the Model. This may seem useless in your example but you will find in many cases the VM's getters/setters need to do some sort of transformation on the values rather than simply passing them through.
class ViewModel:INotifyPropertyChanged
{
private DefineAddinModel model;
public string URL
{
get { return model.URL; }
set
{
if (value != model.URL)
{
model.url = value;
OnPropertyChanged("URL");
}
}
}
public string TemplateType
{
get { return model.TemplateType; }
set
{
if (value != model.TemplateType)
{
model.TemplateType = value;
OnPropertyChanged("TemplateType");
}
}
}
The better way to update your Model Is by using an event, its safer, so choose weather using a button click or lost focus, or whatever you want
void button_click(object sender,eventsarg e)
{
MyObj.URL = App.Locator.MyVM.MyDefineAddinModel.URL;// App.Locator because MVVMLight is tagged
MyObj.TemplateType = App.Locator.MyVM.MyDefineAddinModel.TemplateType ;
}
but personnaly i Use the following steps :
1- In your ViewModel create a CurrentItem object of type DefineAddinModel and without OnPropertyChanged then bind it to the View(UI) DataContext of the RootElement on the View )
2- for the model I use the INotifyPropertyChanged for each propery
3- after binding the datacontext of your root element to the CurrentItem of your ViewModel then bind just URL and TemplateType properties to your Controls, so any thing changes on the textbox will update CurrentItem properties
you can also chose the type of the binding (On LostFocus, or OnPropertyChanged)
You need to bind your TextBoxes to the two properties URL and TemplateType.
Try to use Commands (in the ViewModel)instead of events (in The CodeBehind) since you are in MVVM.
For updating the model : use a button with it's Command property bound to OnSave just like this example:
private String _url;
private String _TemplateType;
private DefineAddinModel _defineAddin;
public DefineAddinModel DefineAddin
{
get {return _defineAddin;}
set
{
_defineAddin = value;
OnPropertyChanged("DefineAddin");
}
}
public string URL
{
get { return _url; }
set
{
if (value != _url)
{
_url= value;
OnPropertyChanged("URL");
}
}
}
public string TemplateType
{
get { return _TemplateType; }
set
{
if (value != _TemplateType)
{
_TemplateType= value;
OnPropertyChanged("URL");
}
}
}
public RelayCommand OnSaved
{
get;
set;
}
public ViewModel()
{
DefineAddin = new DefineAddinModel();
OnSaved = new RelayCommand(()=>
{
DefineAddin.URL = URL ;
DefineAddin.TemplateType = TemplateType;
});
Think about using third parties like MVVMLight it helps you a lot with MVVM and the helpers around it (Commands, Messenger, ViewModelLocator ...)
I think that the correct answer here is 'it depends'.
In most general cases, the advantage of actually using a ViewModel is also to track 'transient state', i.e. the state of an 'edit in progress' operation.
In this particular case, you would not push your changes directly to the Model every time a value is updated, instead you would do this via an 'Update' ICommand implementation that will collect all the data from the ViewModel and push it down to the Model.
This approach gives you many advantages:
The user of the view can change their mind as many times as they want, and only when they are happy will the Model actually get updated with their definitive choices
It greatly reduces the load on your persistence service, since only final changes are pushed through.
It allows you to do final validation on a complete set of values, rather than transient states, and hence reduces programming complexity and overhead.
It also makes your UI far more fluid since all the examples above are pushing updates on the UI Dispatcher, and avoids you having to cater for this via Tasks or other async approaches.
The backing model is never in an inconsistent state, since I would imagine that all values on one View/ViewModel are related, and only make sense when updated together using an ACID approach.
Here's an example of how I'd do it.
public class ViewModel:INotifyPropertyChanged {
private String _url;
private String _TemplateType;
public ViewModel(){
UpdateCommand = new DelegateCommand(OnExecuteUpdate, OnCanExecuteUpdate);
}
public bool OnCanExecuteUpdate(object param){
// insert logic here to return true when one can update
// or false when data is incomplete
}
public void OnExecuteUpdate(object param){
// insert logic here to update your model using data from the view model
}
public ICommand UpdateCommand { get; set;}
public string URL{
get { return _url; }
set {
if (value != _url) {
_url= value;
OnPropertyChanged("URL");
}
}
}
public string TemplateType {
get { return _TemplateType; }
set {
if (value != _TemplateType) {
_TemplateType= value;
OnPropertyChanged("TemplateType");
}
}
}
... etc.
}
public class DelegateCommand : ICommand {
Func<object, bool> canExecute;
Action<object> executeAction;
public DelegateCommand(Action<object> executeAction)
: this(executeAction, null) {}
public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute) {
if (executeAction == null) {
throw new ArgumentNullException("executeAction");
}
this.executeAction = executeAction;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter) {
bool result = true;
Func<object, bool> canExecuteHandler = this.canExecute;
if (canExecuteHandler != null) {
result = canExecuteHandler(parameter);
}
return result;
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged() {
EventHandler handler = this.CanExecuteChanged;
if (handler != null) {
handler(this, new EventArgs());
}
}
public void Execute(object parameter) {
this.executeAction(parameter);
}
}
i was reading a tutorial for windows phone 7 using C# and sliverlight and i found this line
public static class Settings
{
public static readonly Setting<bool> IsRightHanded =
new Setting<bool>("IsRightHanded", true);
public static readonly Setting<double> Threshold =
new Setting<double>("Threshold", 1.5);
}
i can't find the Setting Class in C# i wanted to know if it's under a special namespace or need an additional reference to add
If it is a custom class, and not described in the tutorial you got this from, can you not reimplement it? It looks to me like the class would have a signature something like this:
public class Setting<T>
{
public Setting<T>(string name, T value)
{
Name = name;
Value = value;
}
public string Name { get; set; }
public T Value { get; set; }
}
Of course, there could be more to it than that. What properties are being accessed / bound to on this class in the tutorial?
If you are using "101 Windows Phone 7 Apps" book, Setting class is implemented and explained in Chapter 20.
Here's the Setting<T> class that I use. It supports change notification via INotifyPropertyChanged which is useful for binding (in WPF/SL/etc). It also maintains a copy of the default value so that it may be reset if required.
As a general rule, T should be immutable.
public class Setting<T> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public event Action<T> Changed;
private readonly T _defaultValue;
private T _value;
public Setting(T defaultValue)
{
_defaultValue = defaultValue;
_value = defaultValue;
}
public T Value
{
get { return _value; }
set
{
if (Equals(_value, value))
return;
_value = value;
var evt = Changed;
if (evt != null)
evt(value);
var evt2 = PropertyChanged;
if (evt2 != null)
evt2(this, new PropertyChangedEventArgs("Value"));
}
}
public void ResetToDefault()
{
Value = _defaultValue;
}
}