How to work with a model in viewModel - c#

I'm having a problem with using MVVM for a Xamarin project.
I can not refresh the user interface if one of my objects in my viewModel is updated (after a PUT request, for example).
Let me explain :
My model :
public class MyObject
{
public string Id { get; private set; }
public string Name { get; private set; }
}
My viewmodel :
public class MyViewModel : BaseViewModel
{
public MyObject MyObject { get; private set; }
public string IdMvvm
{
set
{
if (this.MyObject.Id != value)
{
MyObject.Id = value;
OnPropertyChanged(nameof(IdMvvm));
}
}
get { return MyObject.Id; }
}
public string NameMvvm
{
set
{
if (this.MyObject.Name != value)
{
MyObject.Name = value;
OnPropertyChanged(nameof(NameMvvm));
}
}
get { return MyObject.Name; }
}
}
BaseViewModel implements INotifyPropertyChanged
public class BaseViewModel : INotifyPropertyChanged
{
public string PageTitle { get; protected set; }
LayoutViewModel() {}
// MVVM ----------------------------------------------------------------------------------------
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected void SetValue<T>(ref T backingField, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(backingField, value))
return;
backingField = value;
OnPropertyChanged(propertyName);
}
MyViewModel is defined as BindingContext for my page
My properties IdMvvm and NameMvvm are bind in Entry in my page in xaml
When I modify an Entry then the value is raised but if my MyModel object changes value, for example update (click on a button) then the value of the different Entry is not updated
Can you help me please? Because it seems that I missed something ...
If you need more explanation, tell me to know
Sorry if my english is not good

It is because when you change the model, your view is not aware about the change. Update your code so that you explicitly notify property changes when your model changes.
public class MyViewModel : BaseViewModel
{
private MyObject _myObject;
public MyObject MyObject
{
get { return _myObject; }
private set { _myObject = value; NotifyModelChange(); }
}
public string IdMvvm
{
set
{
if (this.MyObject.Id != value)
{
MyObject.Id = value;
OnPropertyChanged(nameof(IdMvvm));
}
}
get { return MyObject.Id; }
}
public string NameMvvm
{
set
{
if (this.MyObject.Name != value)
{
MyObject.Name = value;
OnPropertyChanged(nameof(NameMvvm));
}
}
get { return MyObject.Name; }
}
private void NotifyModelChange()
{
OnPropertyChanged(nameof(IdMvvm));
OnPropertyChanged(nameof(NameMvvm));
}
}

Related

Inheritance with INotifyPropertyChanged

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"));
}
}

Where i need to define INotifyPropertyChanged in case of Base and sub classes

i have this Base class:
public abstract class WiresharkFile
{
protected string _fileName;
protected int _packets;
protected int _packetsSent;
protected string _duration;
public int Packets
{
get { return _packets; }
set { _packets = value; }
}
public int PacketsSent
{
get { return _packetsSent; }
set { _packetsSent = value; }
}
}
And this sub class:
public class Libpcap : WiresharkFile, IDisposable, IEnumerable<WiresharkFilePacket>
{
....
}
Create my object:
WiresharkFile wiresahrkFile = new Libpcap(file);
My collection:
public ObservableCollection<WiresharkFile> wiresharkFiles { get; set; }
Send packets:
wiresahrkFile.Sendpackets();
At this point all my wiresahrkFile (Libpcap type) properties is changing so i wonder where i need to define this INotifyPropertyChanged.
If your xaml is binded to properties of WiresharkFile then a WiresharkFile have to implement the INotifyPropertyChanged, if not it will lead to the memory leaks (Top 3 Memory Leak Inducing Pitfalls of WPF Programming). If your binding is defined only on a Libpcap class then the Libpcap have to implement the INotifyPropertyChanged interface. In my projects I create a base implementation of the INotifyPropertyChanged interface ,and then each base models and base view models just inherits from that implementation. Here some base code:
1. Base implementation:
public class BaseObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> raiser)
{
var propName = ((MemberExpression)raiser.Body).Member.Name;
OnPropertyChanged(propName);
}
protected bool Set<T>(ref T field, T value, [CallerMemberName] string name = null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
OnPropertyChanged(name);
return true;
}
return false;
}
}
2. Your model (in my opinion):
public abstract class WiresharkFile:BaseObservableObject
{
private string _fileName;
private int _packets;
private int _packetsSent;
private string _duration;
public int Packets
{
get { return _packets; }
set
{
_packets = value;
OnPropertyChanged();
}
}
public int PacketsSent
{
get { return _packetsSent; }
set
{
_packetsSent = value;
OnPropertyChanged();
}
}
}
regards,
Same answer with IIan but for C# 8 and .Net Framework 4.8.
1. Base Model
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> raiser)
{
string propName = ((MemberExpression)raiser?.Body).Member.Name;
OnPropertyChanged(propName);
}
protected bool Set<T>(ref T field, T value, [CallerMemberName] string name = null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
OnPropertyChanged(name);
return true;
}
return false;
}
}
2. Your Model
public class Current : ObservableObject
{
private string _status;
public Current()
{
Status = "Not Connected";
}
public string Status
{
get { return _status; }
set
{
_status = value;
OnPropertyChanged(); // call this to update
}
}
}
3. How to use?
<Label Content="{Binding Status}"/>

Binding a nested object to a DataGrid in c# WPF

I am trying to bind the data displayed in a DataGrid to a dynamic list of object (WhisperModel) which is inside another object(WhisperReader). The DataGrid only displays the headers, but no values. How can I make the DataGrid dynamically update itself when the list "whispers" is changed?
Main Window XAML:
<DataGrid x:Name="whisperDataGrid" Margin="10,69,10,10" IsReadOnly="True" ItemsSource="{Binding}"/>
Main Window C#
public partial class MainWindow : Window
{
private WhisperReader wr;
public MainWindow()
{
InitializeComponent();
wr = new WhisperReader();
whisperDataGrid.DataContext = wr.whispers;
}
WhisperReader:
class WhisperReader
{
public ObservableCollection<WhisperModel> whispers { get; private set; }
public WhisperReader()
{
whispers = new ObservableCollection<WhisperModel>();
}
WhisperModel:
class WhisperModel
{
public DateTime sentTime { get; set; }
public string sender { get; set; }
public string message { get; set; }
}
I think your problem is that it doesn't know when to update itself because:
You have made the whispers list the data context.
The properties that you are binding to don't use INotifyPropertyChanged.
WhisperReader and WhisperModel are not public
All bindings must be public, must be properties, and must call the PropertyChanged method.
The PropertyChanged function triggers the binding updates.
Try this...
public partial class MainWindow : Window
{
private WhisperReader wr;
public MainWindow()
{
InitializeComponent();
wr = new WhisperReader();
whisperDataGrid.DataContext = wr;
}
public class WhisperReader : INotifyPropertyChanged
{
ObservableCollection<WhisperModel> _whispers;
public ObservableCollection<WhisperModel> whispers
{
get { return _whispers; }
private set
{
_whispers = value;
NotifyPropertyChanged();
}
}
public WhisperReader()
{
whispers = new ObservableCollection<WhisperModel>();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class WhisperModel : INotifyPropertyChanged
{
public DateTime sentTime { get; set; }
private string _sender;
public string sender
{
get { return _sender; }
set { _sender = value; NotifyPropertyChanged();
}
private string _message;
public string message
{
get { return _message; }
set { _message = value; NotifyPropertyChanged();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<DataGrid x:Name="whisperDataGrid" Margin="10,69,10,10" IsReadOnly="True" AutoGenerateColumns="True" ItemsSource="{Binding whispers}"/>

c# object with a ValueChanged event that fires when each property is changed

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);
}
}

Raising a propertychanged event without adding a private variable

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;

Categories

Resources