Updating dependent property once instead of twice - silverlight

In my ViewModel I have two properties type of Datetime. They are bound in XAML with TwoWay mode. When I update each of them - OnPropertyChanged raises in set part of this Datetime property for the third property. So I want to update the third property only once when I update two Datetime properties at the same time, instead of updating third property twice. How it can be archieved?
Code applied:
//1
public DateTime StartDate
{
...
set
{
this.selectedEndDate = value;
this.OnPropertyChanged("StartDate");
this.OnPropertyChanged("MyList");
}
}
//2
public DateTime EndDate
{
...
set
{
this.selectedEndDate = value;
this.OnPropertyChanged("EndDate");
this.OnPropertyChanged("MyList");
}
}
//third property
public IEnumerable<MyObject> MyList
{
get
{
return _data.Where(kvp=> kvp.Key.Date >= Start && kvp.Value.Date <= End).Select(kvp => kvp.Value);
}
}

You may delay the MyList property change notification by means of a timer that is started whenever one of the date properties changes. This would not only avoid double notifications when both properties change "at the same time", but would also protect against frequent notifications when one of the properties changes too frequently.
The timer would be reset on every property change by stopping and restarting it, hence you can have many subsequent property changes before actually notifying the MyList property change.
The code example below uses a DispatcherTimer to perform this task. Of course you have to find a sensible value for the Interval value.
private DispatcherTimer notifyTimer;
public ViewModel()
{
notifyTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) };
notifyTimer.Tick += OnNotifyTimerTick;
}
private void OnNotifyTimerTick(object sender, EventArgs e)
{
OnPropertyChanged("MyList");
notifyTimer.Stop();
}
public DateTime StartDate
{
...
set
{
selectedEndDate = value;
OnPropertyChanged("StartDate");
notifyTimer.Stop();
notifyTimer.Start();
}
}
public DateTime EndDate
{
...
set
{
selectedEndDate = value;
OnPropertyChanged("EndDate");
notifyTimer.Stop();
notifyTimer.Start();
}
}

As I see it user change startDate fist endDate second. ? or vice versa.
The below code has a chance ,
bool fistChanged,endChanged;
on Ctor (Constructor)
this.PropertyChanged+=(s,p)=>
{
if(p.PropertyName=="firstDate")
{
firstChanged=true;
}
if(p.PropertyName=="endDate")
{
endChanged=true;
}
if(firstChanged && endChanged)
{
this.OnPropertyChanged("MyList");
fistChaned=false;endChanged=false;
}
}

Related

ObservableCollection deep cloning

I've implemented deep cloning of ObservableCollection in order to reset items to It's original state in editable Datagrid, via cancel button.
For this I have two collections - one ObservableCollection to bind Datagrid to It, and cloned List to re-initialize ObservableCollection to It's original state when needed.
My code works only first time I hit a cancel button, after that my cloned List has changes in It too.
Provided code is an example (mine is a bit longer), but It's 100% same as mine:
Model, which implements ICloneable:
public class EmployeeModel : ICloneable
{
public object Clone()
{
return MemberwiseClone();
}
public string NAME
{
get { return _name; }
set
{
if (_name != value)
{
CHANGE = true;
_name = value;
}
}
}
private string _name;
public string SURNAME
{
get { return _surname; }
set
{
if (_surname != value)
{
CHANGE = true;
_surname = value;
}
}
}
private string _surname;
///<summary>Property for tracking changes in model</summary>
public bool CHANGE { get; set; }
}
Viewmodel:
public ViewModel() : Base //Implements InotifyPropertyChanged
{
public ViewModel()
{
Task.Run(()=> GetData());
}
public ObservableCollection<EmployeeModel> Employees
{
get { return _employees; }
set { _employees = value; OnPropertyChanged();}
}
private ObservableCollection<EmployeeModel> _employees;
public List<EmployeeModel> Copy_employees
{
get { return _copy_employees; }
set { _copy_employees = value; OnPropertyChanged();}
}
private List<EmployeeModel> _copy_employees;
//Fetch data from DB
private async Task Get_data()
{
//Returns new ObservableCollection of type Employee
Employees = await _procedures.Get_employees();
if (Employees != null) //Now make a deep copy of Collection
{
Copy_employees = new List<EmployeeModel>();
Copy_employees = Employees.Select(s => (EmployeeModel)s.Clone()).ToList();
}
}
//My Command for canceling changes (reseting DataGrid)
//CanExecute happens, when model is changed - tracking via CHANGE property of EmployeeModel
public void Cancel_Execute(object parameter)
{
Employees.Clear(); //Tried with re-initializing too, but same result
foreach (var item in Copy_employees)// Reset binded ObservableCollection with old items
{
Employees.Add(item);
}
//Check if copied List really hasn't got any changes
foreach (EmployeeModel item in Copy_employees)
{
Console.WriteLine("Changes are " + item.CHANGES.ToString());
}
}
}
Output of cancel command:
1.) First time I hit cancel button:
// Changes are False
Every next time:
// Changes are True
So, as I see It from Console, my copied List get's updated when ObservableColection get's updated, even if It's not binded to DataGrid.
And It updates only a property which I changed, so List reflects ObservableCollection items.
How can I keep my original items of List<Employee>, and copy those into binded ObservableCollection anytime ?
When you return values, you do not return them, but write backing item references to the editable collection.
As a result, you have the same instances in both collections.
In the simplest case, when you return them, you also need to clone.
public void Cancel_Execute(object parameter)
{
Employees.Clear(); //Tried with re-initializing too, but same result
foreach (var item in Copy_employees)// Reset binded ObservableCollection with old items
{
Employees.Add((EmployeeModel)item.Clone());
}
//Check if copied List really hasn't got any changes
foreach (EmployeeModel item in Copy_employees)
{
Console.WriteLine("Changes are " + item.CHANGES.ToString());
}
}
Not relevant to the question, but I still advise you to use a slightly more user-friendly interface for cloneable:
public interface ICloneable<T> : ICloneable
{
new T Clone();
}

How do i detect a WPFDataGrid row Data changed?

I have a DataGrid,and need to detect when a user has make changes to a row.I don't want to use CellEditEnding because whenever a row get focus and lost it without any inputs,this event get raised,in the other way i need to bind a bool property to each row that set to true when the row got chgangd.
Use following code as an example, so you know the basic idea of how to trace if an item in your ItemSource had been changed (here only compared to the initial value only).
List<myItem> Items=new List<myItem>(); //your ItemSource
class myItem:ObservableObject //an class implement INotifyPropertyChanged interface
{
string _inititemName;
string _itemName;
bool itemChanged; //here is your indicator
myItem(string name)
{
_inititemName=itemName=name;
}
public string itemName
{
get{return _itemName;}
set
{
_itemName=vlaue;
if (_itemName!=_inititemName)
itemChanged=true;
else
itemChanged=false;
RaisePropertyChanged("itemName"); //or whatever the name of the method is that invoke OnPropertyChanged
}
}
}
Make the properties of your item class set a boolean update flag when they are modified
e.g.
public class MyGridItem
{
public MyGridItem(string Name)
{
this.Name = Name;
Updated = false;
}
public bool Updated {get; private set;}
private string _Name = null;
public string Name
{
get { return _Name; }
set {
if (!_Name.Equals( value ))
{
_Name = value;
Updated = true
}
}
}
}

How to Notify That View Should Get New Value of Calculated Field

I am working on a WP7 app that displays some times on one page. I have a code behind that has an ObservableCollection of objects. Each object has a calculated property that uses DateTime.Now to determine the time that's displayed on the page. I can't figure out how to "notify" that the property has changed since the property doesn't change, the current time is changing (just once per second). Any ideas? Here's the jist of what I've got:
//my business object
public class Widget
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private DateTime? _start;
public DateTime? Start
{
get { return _start; }
set { _start = value; }
}
public TimeSpan? TimeSinceStart
{
get { return Start.HasValue ? DateTime.Now - Start.Value : default(TimeSpan); }
}
}
//my viewmodel
public class WidgetDisplayerViewModel : BaseViewModel
{
public WidgetDisplayerViewModel()
{
TimeUpdateTimer.Tick += new EventHandler(TimeUpdateTimer_Tick);
TimeUpdateTimer.Interval = new TimeSpan(0, 0, 1);
TimeUpdateTimer.Start();
}
public WidgetDisplayerViewModel(string selectedCategory) : this()
{
Category = MockDataService.GetCategory(selectedCategory);
Category.Widgets = MockDataService.GetWidgets(selectedCategory).ToObservableCollection();
}
public DispatcherTimer TimeUpdateTimer = new DispatcherTimer();
private DateTime _currentTime;
public DateTime CurrentTime
{
get { return _currentTime; }
set {
_currentTime = value;
NotifyPropertyChanged("CurrentTime");
}
}
public Category Category { get; set; }
void TimeUpdateTimer_Tick(object sender, EventArgs e)
{
CurrentTime = DateTime.Now;
}
}
And then the view is very simple and just needs to display the CurrentTime and then for each Widget in the collection it needs to show the TimeSinceStart. The CurrentTime is getting updated each second by the timer and that gets propogated to the view. That one is easy because the timer is setting it and so I have a chance to call NotifyPropertyChanged("CurrentTime"), but how would I "notify" that all of the TimeSinceStart getters should be called to update the calculated value for each Widget since I'm not setting them?
Thanks!
You'll have to manually refresh the property one way or another. I see you already have a timer ticking every second. So I can suggest you two solutions:
1/ Define a "UpdateTime" method in the Widget object. In this method, call NotifyPropertyChanged("TimeSinceStart"). When the timer is ticking, enumerate the list of widgets, and call the UpdateTime method on each.
2/ Create a global object implementing the INotifyPropertyChanged interface, and holding the value of CurrentTime. Make each of your Widget objects subscribe to the PropertyChanged event of this global class to know when the time is updated. Then, when the event is triggered, call NotifyPropertyChanged("TimeSinceStart").
This can be a tricky one to work out and it can get very messy very fast.
I would suggest you stick with your current approach of having only one timer which is initialised in the main viewmodel. You then have to ask yourself the question - does the age (TimeSinceStart) of the Widget belong on the Widget, or is it purely for display/informational purposes? Is it a core piece of information that each Widget must keep during its lifespan?
This looks to me like it is for display purposes only. So my suggestion is this: once you have called GetWidgets, you could enumerate through each Widget and wrap it in a thin viewmodel of its own. The constructor for that viewmodel takes two parameters - the timer from the main viewmodel, and the Widget. You then subscribe to the timer's Tick event, and from that you notify that the TimeSinceStart property has changed.
public class WidgetWrapper : INotifyPropertyChanged
{
public WidgetWrapper(DispatcherTimer timer, Widget widget)
{
_widget = widget;
timer.Tick += TimerTick;
}
private void TimerTick(object sender, EventArgs e)
{
OnPropertyChanged("TimeSinceStart");
}
public Widget Widget { get { return _widget; } }
public TimeSpan? TimeSinceStart
{
get { return _widget.Start.HasValue ? DateTime.Now - _widget.Start.Value : default(TimeSpan); }
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
private readonly Widget _widget;
}
public class WidgetDisplayerViewModel : BaseViewModel
{
public WidgetDisplayerViewModel(string selectedCategory) : this()
{
Category = MockDataService.GetCategory(selectedCategory);
var wrappedWidgets = new ObservableCollection<WidgetWrapper>();
MockDataService.GetWidgets(selectedCategory).ForEach(widget => wrappedWidgets.Add(new WidgetWrapper(TimeUpdateTimer, widget)));
Category.Widgets = wrappedWidgets;
}
}
Wrapping a DTO (entity, Data Transfer Object) with its own viewmodel is a quite common approach when adding functionality to an entity. If you use this appoach you will have to slightly modify any UI bindings that were targetting properties on the Widget, as those UI elements will now be dealing with a WidgetWrapper (or you can just surface the required properties in the WidgetWrapper itself, then no bindings have to change).
Invoke the NotifyPropertyChanged method for the specified property.
public DateTime CurrentTime
{
get { return _currentTime; }
set {
_currentTime = value;
NotifyPropertyChanged("CurrentTime");
NotifyPropertyChanged("TimeSinceStart");
}
}
Subscribe all widgets to CurrentTime PropertyChanged event in Widget constructor
private Widget()
{
App.ViewModel.PropertyChanged += (s, e) =>
{
if (e.PropertyName.Equals("CurrentTime")
{
NotifyPropertyChanged("TimeSinceStart");
}
};
}

How can I validate multiple properties when any of them changes?

I have two date fields: StartDate and EndDate. StartDate must be earlier than EndDate.
If the user changes the StartDate to something greater than the EndDate, a red border appears around that DatePicker, and vise versa. If the user changes the 2nd box so that the date range is now correct, the 1st box still has the Validation Error.
How can I validate both date fields when either one of them changes?
I'm using IDataErrorInfo
public string GetValidationError(string propertyName)
{
switch (propertyName)
{
case "StartDate":
if (StartDate > EndDate)
s = "Start Date cannot be later than End Date";
break;
case "EndDate":
if (StartDate > EndDate)
s = "End Date cannot be earlier than Start Date";
break;
}
return s;
}
I cannot simply raise a PropertyChange event because I need to validate both fields when either of them changes, so having both of them raise a PropertyChange event for the other will get stuck in an infinite loop.
I also do not like the idea of clearing the Date field if the other date returns a validation error.
The simplest way is to raise a PropertyChanged notification for in the setter for both properties that need to be validated like bathineni suggests
private DateTime StartDate
{
get { return _startDate; }
set
{
if (_startDate != value)
{
_startDate = value;
RaisePropertyChanged("StartDate");
RaisePropertyChanged("EndDate");
}
}
}
private DateTime EndDate
{
get { return _endDate; }
set
{
if (_endDate!= value)
{
_endDate= value;
RaisePropertyChanged("StartDate");
RaisePropertyChanged("EndDate");
}
}
}
However if that doesn't work for you, I figured out one way to validate a group of properties together, although your classes have to implement INotifyPropertyChanging in addition to INotifyPropertyChanged (I'm using EntityFramework and by default their classes implement both interfaces)
Extension Method
public static class ValidationGroup
{
public delegate string ValidationDelegate(string propertyName);
public delegate void PropertyChangedDelegate(string propertyName);
public static void AddValidationGroup<T>(this T obj,
List<string> validationGroup, bool validationFlag,
ValidationDelegate validationDelegate,
PropertyChangedDelegate propertyChangedDelegate)
where T : INotifyPropertyChanged, INotifyPropertyChanging
{
// This delegate runs before a PropertyChanged event. If the property
// being changed exists within the Validation Group, check for validation
// errors on the other fields in the group. If there is an error with one
// of them, set a flag to true.
obj.PropertyChanging += delegate(object sender, PropertyChangingEventArgs e)
{
if (validationGroup.Contains(e.PropertyName))
{
foreach(var property in validationGroup)
{
if (validationDelegate(property) != null)
{
validationFlag = true;
break;
}
}
}
};
// After the Property gets changed, if another field in this group was
// invalid prior to the change, then raise the PropertyChanged event for
// all other fields in the Validation Group to update them.
// Also turn flag off so it doesn't get stuck in an infinite loop
obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
if (validationGroup.Contains(e.PropertyName))
{
if (validationFlag && validationDelegate(e.PropertyName) == null)
{
validationFlag = false;
foreach(var property in validationGroup)
{
propertyChangedDelegate(property);
}
}
}
};
}
}
To use it, add the following call to the constructor of any class that should validate a group of properties together.
this.AddValidationGroup(
new List<string> { "StartDate", "EndDate" },
GetValidationError, OnPropertyChanged);
I've tested this with up to 3 properties in a Validation Group and it seems to work OK.
Use this trick, it prevents they call OnPropertyChanged each other :
private bool RPCfromStartDate = false;
private bool RPCfromEndDate = false;
public string this[string columnName]
{
get
{
string result = null;
switch (columnName)
{
case "StartDate":
if (StartDate.Date >= EndDate.Date)
{
result = "Start Date cannot be later than End Date";
}
if (!RPCfromEndDate)
{
RPCfromStartDate = true;
OnPropertyChanged("EndDate");
RPCfromStartDate = false;
}
case "EndDate":
if (StartDate.Date >= EndDate.Date)
{
result = "End Date cannot be earlier than Start Date";
}
if (!RPCfromStartDate)
{
RPCfromEndDate = true;
OnPropertyChanged("StartDate");
RPCfromEndDate = false;
}
break;
}
...
I generally add all of my validation errors to a dictionary, and have the validation template subscribe to that via the property name. In each property changed event handler, I can check any number of properties and add or remove their validation status as necessary.
Check this answer for how my implementation looks. Sorry it is in VB.NET, but should be fairly straightforward.
You can also subscribe to the SelectedDateChanged event handler and update needed binding.
BindingExpression expression = datePickerStartDate.GetBindingExpression(DatePicker.SelectedDateProperty);
if (expression != null)
{
expression.UpdateSource();
}

PropertyChanged notification for calculated properties

I'm developing an application in Silverlight2 and trying to follow the Model-View-ViewModel pattern. I am binding the IsEnabled property on some controls to a boolean property on the ViewModel.
I'm running into problems when those properties are derived from other properties. Let's say I have a Save button that I only want to be enabled when it's possible to save (data has been loaded, and we're currently not busy doing stuff in the database).
So I have a couple of properties like this:
private bool m_DatabaseBusy;
public bool DatabaseBusy
{
get { return m_DatabaseBusy; }
set
{
if (m_DatabaseBusy != value)
{
m_DatabaseBusy = value;
OnPropertyChanged("DatabaseBusy");
}
}
}
private bool m_IsLoaded;
public bool IsLoaded
{
get { return m_IsLoaded; }
set
{
if (m_IsLoaded != value)
{
m_IsLoaded = value;
OnPropertyChanged("IsLoaded");
}
}
}
Now what I want to do is this:
public bool CanSave
{
get { return this.IsLoaded && !this.DatabaseBusy; }
}
But note the lack of property-changed notification.
So the question is: What is a clean way of exposing a single boolean property I can bind to, but is calculated instead of being explicitly set and provides notification so the UI can update correctly?
EDIT: Thanks for the help everyone - I got it going and had a go at making a custom attribute. I'm posting the source here in case anyone's interested. I'm sure it could be done in a cleaner way, so if you see any flaws, add a comment or an answer.
Basically what I did was made an interface that defined a list of key-value pairs to hold what properties depended on other properties:
public interface INotifyDependentPropertyChanged
{
// key,value = parent_property_name, child_property_name, where child depends on parent.
List<KeyValuePair<string, string>> DependentPropertyList{get;}
}
I then made the attribute to go on each property:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class NotifyDependsOnAttribute : Attribute
{
public string DependsOn { get; set; }
public NotifyDependsOnAttribute(string dependsOn)
{
this.DependsOn = dependsOn;
}
public static void BuildDependentPropertyList(object obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
var obj_interface = (obj as INotifyDependentPropertyChanged);
if (obj_interface == null)
{
throw new Exception(string.Format("Type {0} does not implement INotifyDependentPropertyChanged.",obj.GetType().Name));
}
obj_interface.DependentPropertyList.Clear();
// Build the list of dependent properties.
foreach (var property in obj.GetType().GetProperties())
{
// Find all of our attributes (may be multiple).
var attributeArray = (NotifyDependsOnAttribute[])property.GetCustomAttributes(typeof(NotifyDependsOnAttribute), false);
foreach (var attribute in attributeArray)
{
obj_interface.DependentPropertyList.Add(new KeyValuePair<string, string>(attribute.DependsOn, property.Name));
}
}
}
}
The attribute itself only stores a single string. You can define multiple dependencies per property. The guts of the attribute is in the BuildDependentPropertyList static function. You have to call this in the constructor of your class. (Anyone know if there's a way to do this via a class/constructor attribute?) In my case all this is hidden away in a base class, so in the subclasses you just put the attributes on the properties. Then you modify your OnPropertyChanged equivalent to look for any dependencies. Here's my ViewModel base class as an example:
public class ViewModel : INotifyPropertyChanged, INotifyDependentPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
// fire for dependent properties
foreach (var p in this.DependentPropertyList.Where((x) => x.Key.Equals(propertyname)))
{
PropertyChanged(this, new PropertyChangedEventArgs(p.Value));
}
}
}
private List<KeyValuePair<string, string>> m_DependentPropertyList = new List<KeyValuePair<string, string>>();
public List<KeyValuePair<string, string>> DependentPropertyList
{
get { return m_DependentPropertyList; }
}
public ViewModel()
{
NotifyDependsOnAttribute.BuildDependentPropertyList(this);
}
}
Finally, you set the attributes on the affected properties. I like this way because the derived property holds the properties it depends on, rather than the other way around.
[NotifyDependsOn("Session")]
[NotifyDependsOn("DatabaseBusy")]
public bool SaveEnabled
{
get { return !this.Session.IsLocked && !this.DatabaseBusy; }
}
The big caveat here is that it only works when the other properties are members of the current class. In the example above, if this.Session.IsLocked changes, the notification doesnt get through. The way I get around this is to subscribe to this.Session.NotifyPropertyChanged and fire PropertyChanged for "Session". (Yes, this would result in events firing where they didnt need to)
The traditional way to do this is to add an OnPropertyChanged call to each of the properties that might affect your calculated one, like this:
public bool IsLoaded
{
get { return m_IsLoaded; }
set
{
if (m_IsLoaded != value)
{
m_IsLoaded = value;
OnPropertyChanged("IsLoaded");
OnPropertyChanged("CanSave");
}
}
}
This can get a bit messy (if, for example, your calculation in CanSave changes).
One (cleaner? I don't know) way to get around this would be to override OnPropertyChanged and make the call there:
protected override void OnPropertyChanged(string propertyName)
{
base.OnPropertyChanged(propertyName);
if (propertyName == "IsLoaded" /* || propertyName == etc */)
{
base.OnPropertyChanged("CanSave");
}
}
You need to add a notification for the CanSave property change everywhere one of the properties it depends changes:
OnPropertyChanged("DatabaseBusy");
OnPropertyChanged("CanSave");
And
OnPropertyChanged("IsEnabled");
OnPropertyChanged("CanSave");
How about this solution?
private bool _previousCanSave;
private void UpdateCanSave()
{
if (CanSave != _previousCanSave)
{
_previousCanSave = CanSave;
OnPropertyChanged("CanSave");
}
}
Then call UpdateCanSave() in the setters of IsLoaded and DatabaseBusy?
If you cannot modify the setters of IsLoaded and DatabaseBusy because they are in different classes, you could try calling UpdateCanSave() in the PropertyChanged event handler for the object defining IsLoaded and DatabaseBusy.

Resources