In my Model and ViewModel for XAML View (List), I have a String property.
The data are retrieved in LoadData from a WebService.
I don't use MVVMlight.
Model:
public class LocationsModel : INotifyPropertyChanged
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (value != _name)
{
_name = value;
NotifyPropertyChanged("Name");
}
}
}
private string _id;
public string ID
{
get
{
return _id;
}
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged("ID");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
ViewModel:
public class MainViewSurroundingModel : INotifyPropertyChanged
{
public MainViewSurroundingModel()
{
this.Items = new ObservableCollection<LocationsModel>();
}
public ObservableCollection<LocationsModel> Items { get; set; }
private string _name = "";
private string _id = "";
public string Name
{
get
{
return _name;
}
set
{
if (value != _name)
{
_name = value;
NotifyPropertyChanged("Name");
}
}
}
public string ID
{
get
{
return _id;
}
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged("ID");
}
}
}
public bool IsDataLoaded
{
get;
private set;
}
public async Task<bool> LoadData()
{
// WEB-API CALL IS HERE...
this.IsDataLoaded = true;
return true;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I now want to update the Name property periodically by code (not re-retrieving data from WebService) every 5 minutes.
How and where can I implement this?
Sorry for vague answer, don't have much time so if anyone else cares to write more about what I said, they are welcome to it.
How to
One of the possibilities is using DispatcherTimer (more about it for example here) and using it's Tick event.(there is a tutorial in the link provided)
Now about where to create your timer.
It depends on what you want to change and when you want to start it.
If I'd like to change ALL of the data in the list some predefined way, i can do it like this:
public class MainViewSurroundingModel : INotifyPropertyChanged
{
//...omitted the parts you have done, only writing the things I'd change...
MainViewSurroundingModel()
{
..if there was something leave it here..
changeTimer = new DispatcherTimer...
changeTimer.Tick += Tick;
changeTimer.Interval = ....et cetera, setting the timer based on tutorial
}
public ObservableCollection<LocationsModel> items;
public ObservableCollection<LocationsModel> Items
{
get //edited so that I can write my own setter
{
return items;
}
set
{
if(value != items)
{
items = value;
//NotifyPropertyChanged("Items"); //can be used here, not necessary
changeTimer.Start();
}
}
}
private DispatcherTimer changeTimer;//based on the tutorial
//based on the tutorial provided, create dispatcher timer and
//tick definition somewhere around here
private Tick(...)
{
//code that iterates through the list and updates it goes here!
}
}
Related
i'm having difficulties deserialising a json file. The json object has the following structure which has been simplified
{"date":"2015-11-11",
"retailer_id":"CLD001",
"orders":[{
"products":
[{
"product_id":"53743443003",
"quantity":4,"
unit_price":42.71}],
"value":170.84,
"customer":{"id":58}}]}
This structure indicated to me that the top class is
[Table]
public class RetailOrders : INotifyPropertyChanged, INotifyPropertyChanging
{
private List<OrderItems> oi;
private string retailer_id;
private DateTime date;
public List<OrderItems> OrderItems
{
get { return oi; }
set { oi = value; }
}
public string Retailer_id
{
get { return retailer_id; }
set { retailer_id = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
}
As you can see orders take a list of products being ordered with the variable id, quantity and total price
[Table]
public class ProductsOrdered: INotifyPropertyChanged, INotifyPropertyChanging
{
private string productID;
private int quantity;
private double unit_price;
public string ProductID
{
get { return productID; }
set { productID = value; }
}
public int Quantity
{
get { return quantity; }
set { quantity = value; }
}
public double UnitPrice
{
get { return unit_price; }
set { unit_price = value; }
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
finally the orderItems contain a list of the orders followed by a total price and associated customer
[Table]
public class OrderItems : INotifyPropertyChanged, INotifyPropertyChanging
{
private List<ProductsOrdered> po = new List<ProductsOrdered>();
private double TotalPrice;
private int customer_id;
public List<ProductsOrdered> Productsordered
{
get { return po; }
set { po = value; }
}
public double totalprice
{
get { return TotalPrice; }
set { TotalPrice = value; }
}
public int customerid
{
get { return customer_id; }
set { customer_id = value; }
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
}
I'm expecting the list to fill out however currently they are null values and can't seem to think of why this is happening
Your property names don't match the JSON you've supplied. Specifically in your JSON there is an array orders but in your C# class the property is OrderItems.
You could annotate the property like this:
[JsonProperty(PropertyName = "orders")]
public List<OrderItems> OrderItems { get; set; }
I haven't worked all the way through your hierarchy, but any other null fields will likely be caused by a similar mismatch.
One other thing to be careful of is private properties and private setters, which I don't thing will be an issue for you here, but is the other top reason for null values when you deserialize JSON.
I was wondering if anyone knows how to solve the following problem... I have a base class that needs to update it's modifiedDateTime property when a derived class property is changed.
BaseObject.cs
public class BaseObject
{
private DateTime? _modifiedDateTime;
public DateTime? modifiedDateTime
{
get { return _modifiedDateTime ; }
set { _modifiedDateTime = value; }
}
public BaseObject
{
_modifiedDateTime = DateTime.Now.ToUniversalTime();
}
public void Update(object sender, PropertyChangedEventArgs e)
{
_modifiedDateTime = DateTime.Now.ToUniversalTime();
}
}
ExampleClass1.cs
public class ExampleClass1: BaseObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _data;
public int data
{
get { return _data; }
set
{
_data = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("data"));
}
}
public ExampleClass1()
{
PropertyChanged += base.Update;
}
}
The previous example is working as expected.
However if the derived class contains an object of another class. For example:
ExampleClass2.cs
public class ExampleClass2: BaseObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _data;
private ExampleClass1 _objClass1;
public int data
{
get { return _data; }
set
{
_data = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("data"));
}
}
public ExampleClass1 objClass1
{
get { return _objClass1; }
set
{
_objClass1 = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("objClass1"));
}
}
public ExampleClass2()
{
PropertyChanged += base.Update;
}
}
When I change the data property of the objClass1, the modifiedDateTime property of the ExampleClass2 inherited by the base class BaseObject is not updated.
How can I solve this problem?
When you set the value of objClass1 subscribe to its property changed event as well
public ExampleClass1 objClass1 {
get { return _objClass1; }
set {
//in case one already existed. unsubscribe from event
if(_objClass1 != null) _objClass1.PropertyChanged -= base.Update
_objClass1 = value;
//subscribe to event
if(_objClass1 != null) _objClass1.PropertyChanged += base.Update
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("objClass1"));
}
}
What is the best way to create a class with an event that fires when one of its Properties is changed? Specifically, how do you convey to any subscribers which Property was changed?
Ex:
public class ValueChangedPublisher
{
private int _prop1;
private string _prop2;
public static event ValueChangedHandler(/*some parameters?*/);
public int Prop1
{
get { return _prop1; }
set
{
if (_prop1 != value)
{
_prop1 = value;
ValueChangedHandler(/*parameters?*/);
}
}
}
public string Prop2
{
get { return _prop2; }
set
{
if (_prop2 != value)
{
_prop2 = value;
ValueChangedHandler(/*parameters?*/);
}
}
}
}
public class ValueChangedSubscriber
{
private int _prop1;
private string _prop2;
public ValueChangedSubscriber()
{
ValueChangedPublisher.ValueChanged += ValueChanged;
}
private void ValueChanged(/*parameters?*/)
{
/*how does the subscriber know which property was changed?*/
}
}
My goal is to make this as extensible as possible (e.g. I don't want a bunch of huge if/else if/switch statements lumbering around). Does anybody know of a technique to achieve what I'm looking for?
EDIT:
What I'm really looking for is how to utilize the INotifyPropertyChanged pattern on the subscriber side. I don't want to do this:
private void ValueChanged(string propertyName)
{
switch(propertyName)
{
case "Prop1":
_prop1 = _valueChangedPublisher.Prop1;
break;
case "Prop2":
_prop2 = _valueChangedPublisher.Prop2;
break;
// the more properties that are added to the publisher, the more cases I
// have to handle here :/ I don't want to have to do it this way
}
}
.NET provides the INotifyPropertyChanged interface. Inherit and implement it:
public class ValueChangedPublisher : INotifyPropertyChanged
{
private int _prop1;
private string _prop2;
public event PropertyChangedEventHandler ValueChangedHandler;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public int Prop1
{
get { return _prop1; }
set
{
if (_prop1 != value)
{
_prop1 = value;
NotifyPropertyChanged();
}
}
}
public string Prop2
{
get { return _prop2; }
set
{
if (_prop2 != value)
{
_prop2 = value;
NotifyPropertyChanged();
}
}
}
}
Here is what I did to solve my problem. It's a bit large, so maybe not performant, but works for me.
Edit
See this question for performance details: C# using properties with value types with Delegate.CreateDelegate
Base Class for publishing property change stuff:
public abstract class PropertyChangePublisherBase : INotifyPropertyChanged
{
private Dictionary<string, PropertyInfo> _properties;
private bool _cacheProperties;
public bool CacheProperties
{
get { return _cacheProperties; }
set
{
_cacheProperties = value;
if (_cacheProperties && _properties == null)
_properties = new Dictionary<string, PropertyInfo>();
}
}
protected PropertyChangePublisherBase(bool cacheProperties)
{
CacheProperties = cacheProperties;
}
public bool ContainsBinding(PropertyChangedEventHandler handler)
{
if (PropertyChanged == null)
return false;
return PropertyChanged.GetInvocationList().Contains(handler);
}
public object GetPropertValue(string propertyName)
{
if (String.IsNullOrEmpty(propertyName) || String.IsNullOrWhiteSpace(propertyName))
throw new ArgumentException("Argument must be the name of a property of the current instance.", "propertyName");
return ProcessGetPropertyValue(propertyName);
}
protected virtual object ProcessGetPropertyValue(string propertyName)
{
if (_cacheProperties)
{
if (_properties.ContainsKey(propertyName))
{
return _properties[propertyName].GetValue(this, null);
}
else
{
var property = GetType().GetProperty(propertyName);
_properties.Add(propertyName, property);
return property.GetValue(this, null);
}
}
else
{
var property = GetType().GetProperty(propertyName);
return property.GetValue(this, null);
}
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Base Class for receiving property change stuff:
public abstract class PropertyChangeSubscriberBase
{
protected readonly string _propertyName;
protected virtual object Value { get; set; }
protected PropertyChangeSubscriberBase(string propertyName, PropertyChangePublisherBase bindingPublisher)
{
_propertyName = propertyName;
AddBinding(propertyName, this, bindingPublisher);
}
~PropertyChangeSubscriberBase()
{
RemoveBinding(_propertyName);
}
public void Unbind()
{
RemoveBinding(_propertyName);
}
#region Static Fields
private static List<string> _bindingNames = new List<string>();
private static List<PropertyChangeSubscriberBase> _subscribers = new List<PropertyChangeSubscriberBase>();
private static List<PropertyChangePublisherBase> _publishers = new List<PropertyChangePublisherBase>();
#endregion
#region Static Methods
private static void PropertyChanged(object sender, PropertyChangedEventArgs args)
{
string propertyName = args.PropertyName;
if (_bindingNames.Contains(propertyName))
{
int i = _bindingNames.IndexOf(propertyName);
var publisher = _publishers[i];
var subscriber = _subscribers[i];
subscriber.Value = publisher.GetPropertValue(propertyName);
}
}
public static void AddBinding(string propertyName, PropertyChangeSubscriberBase subscriber, PropertyChangePublisherBase publisher)
{
if (!_bindingNames.Contains(propertyName))
{
_bindingNames.Add(propertyName);
_publishers.Add(publisher);
_subscribers.Add(subscriber);
if (!publisher.ContainsBinding(PropertyChanged))
publisher.PropertyChanged += PropertyChanged;
}
}
public static void RemoveBinding(string propertyName)
{
if (_bindingNames.Contains(propertyName))
{
int i = _bindingNames.IndexOf(propertyName);
var publisher = _publishers[i];
_bindingNames.RemoveAt(i);
_publishers.RemoveAt(i);
_subscribers.RemoveAt(i);
if (!_publishers.Contains(publisher))
publisher.PropertyChanged -= PropertyChanged;
}
}
#endregion
}
Actual class to use for subscribing to property change stuff:
public sealed class PropertyChangeSubscriber<T> : PropertyChangeSubscriberBase
{
private PropertyChangePublisherBase _publisher;
public new T Value
{
get
{
if (base.Value == null)
return default(T);
if (base.Value.GetType() != typeof(T))
throw new InvalidOperationException(String.Format("Property {0} on object of type {1} does not match the type Generic type specified {2}.", _propertyName, _publisher.GetType(), typeof(T)));
return (T)base.Value;
}
set { base.Value = value; }
}
public PropertyChangeSubscriber(string propertyName, PropertyChangePublisherBase bindingPublisher)
: base(propertyName, bindingPublisher)
{
_publisher = bindingPublisher;
}
}
Here is an example of the Class with properties that you wish to be notified about:
public class ExamplePublisher: PropertyChangedPublisherBase
{
private string _id;
private bool _testBool;
public string Id
{
get { return _id; }
set
{
if (value == _id) return;
_id = value;
RaisePropertyChanged("Id");
}
}
public bool TestBool
{
get { return _testBool; }
set
{
if (value.Equals(_testBool)) return;
_testBool = value;
RaisePropertyChanged("TestBool");
}
}
}
Here is an example of the Class that will be notified when the properties in the class above change:
public class ExampleReceiver
{
public PropertyChangeSubscriber<string> Id { get; set; }
public PropertyChangeSubscriber<bool> TestBool { get; set; }
public MyExampleClass(PropertyChangePublisherBase publisher)
{
Id = new PropertyChangeSubscriber<string>("Id", publisher);
TestBool = new PropertyChangeSubscriber<bool>("TestBool", publisher);
}
}
This approach seems to work half the time for me.
I can see these lines get executed in the debugger:
agencyListBox.DataBindings.Add(new Binding("DataSource", this.Data.Agencies, "AvailableAgencies"));
agencyListBox.DataBindings.Add(new Binding("SelectedItem", this.Data.Agencies, "SelectedAgency", false, DataSourceUpdateMode.OnPropertyChanged));
The agencies class looks like this:
public AgencyType SelectedAgency
{
get
{
return _selected;
}
set
{
_selected = value;
OnPropertyChanged("SelectedAgency");
}
}
public List<AgencyType> AvailableAgencies
{
get
{
return _availableList;
}
set
{
_availableList = value;
OnPropertyChanged("AvailableAgencies");
}
}
So the fields I reference in the binding do exist.
The DisplayMember is set to "Label" which is defined in the AgencyType class:
public event PropertyChangedEventHandler PropertyChanged;
private string _label { get; set; }
public string Label
{
get { return _label; }
set
{
_label = value;
OnPropertyChanged("Label");
}
}
private string _identifier { get; set; }
public string Identifier
{
get { return _identifier; }
set
{
_identifier = value;
OnPropertyChanged("Identifier");
}
}
public AgencyType()
{
Label = string.Empty;
Identifier = string.Empty;
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The values are displayed as desired.
But then when I change the selection, data.Agencies.SelectedAgency is null!
Does anyone have any tips?
I have a property which looks like this.
public int NumberOfElephants { get; set; }
this property is in an observablecollection and it has to notify another property that it has changed.
how would i do the following
public int NumberOfElephants { get; set { OnPropertyChanged("totalAnimals"); }
without the code needing to be like this
private int _numberOfElephants;
public int NumberOfElephants {
get {
return _numberOfElephants;
}
set {
_numberOfElephants = value;
OnPropertyChanged("totalAnimals");
}
}
You don't. You can't.
Automatically implemented propertieS only work when the property is trivial - when no code is needed for the get/set beyond "return the variable's value" or "set the variable's value". You can make it shorter with reformatting, of course... I'd write that as:
private int numberOfElephants;
public int NumberOfElephants {
get { return numberOfElephants; }
set {
_numberOfElephants = value;
OnPropertyChanged("totalAnimals");
}
}
Actually, I'd use "opening brace on a line on its own" for the start of the set and the start of the property, but I've kept your favoured style for those. But having "single expression get/set implementations" on a single line can make classes with lots of properties much cleaner.
As an alternative to Jon's answer, you can get tools that will do this via IL weaving, such as NotifyPropertyWeaver, also available as a tool through the VS Gallery
For your sample, you should be able to have something like the following, according to their doco on Attributes:
[NotifyProperty(AlsoNotifyFor = new[] { "TotalAnimals" })]
public int NumberOfElephants { get; set; }
public int TotalAnimals { get; set; }
However, based on the example below from their site it might not be required depending on the implementation of TotalAnimals:
Your Code
public class Person : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public string GivenNames { get; set; }
public string FamilyName { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
}
What gets compiled
public class Person : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
string givenNames;
public string GivenNames
{
get { return givenNames; }
set
{
if (value != givenNames)
{
givenNames = value;
OnPropertyChanged("GivenNames");
OnPropertyChanged("FullName");
}
}
}
string familyName;
public string FamilyName
{
get { return familyName; }
set
{
if (value != familyName)
{
familyName = value;
OnPropertyChanged("FamilyName");
OnPropertyChanged("FullName");
}
}
}
public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
public virtual void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Expanding on the answer by #jeffora
Using NotifyPropertyWeaver you could write this
public class Animals: INotifyPropertyChanged
{
public int NumberOfElephants { get; set; }
public int NumberOfMonkeys { get; set; }
public int TotalAnimals
{
get
{
return NumberOfElephants + NumberOfMonkeys;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
And this would be compiled
public class Animals : INotifyPropertyChanged
{
int numberOfElephants;
int numberOfMonkeys;
public int NumberOfElephants
{
get { return numberOfElephants; }
set
{
numberOfElephants = value;
OnPropertyChanged("TotalAnimals");
OnPropertyChanged("NumberOfElephants");
}
}
public int NumberOfMonkeys
{
get { return numberOfMonkeys; }
set
{
numberOfMonkeys = value;
OnPropertyChanged("TotalAnimals");
OnPropertyChanged("NumberOfMonkeys");
}
}
public int TotalAnimals
{
get { return NumberOfElephants + NumberOfMonkeys; }
}
public virtual void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
With tool like PostSharp you can weave the property to create the boiler plate code code. More, you don't have to implement the INotifyPropertyChanged, PostSharp can do it for you.
See this blog post.
I would use this in C#6
private int numberOfElephants;
public int NumberOfElephants {
get => numberOfElephants;
set {
_numberOfElephants = value;
OnPropertyChanged();
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
This needs
using System.Runtime.CompilerServices;