I have fiddled around with MVVM lately in C# and i got to the point where i thought i understood how bindings work but then this happened...
using System;
using System.Collections.Generic;
using System.Text;
namespace API
{
public class ApiViewModel : BaseViewModel
{
public bool CustomerIsChecked { get; set; }
public bool StorageIsChecked { get; set; }
public bool ArticlesIsChecked { get; set; }
public bool Transfer()
{
if(CustomerIsChecked == true)
{
return true;
}
return false;
}
public override string ToString()
{
return Transfer().ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using PropertyChanged;
namespace API
{
[AddINotifyPropertyChangedInterface]
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };
}
}
This works if i just like send in a string or anything to the binding directly but when i try to send in the value of transfer it does not work it gives me an empty button why is this? My question is why this doesnt work quz basicly when you are using a string without any parameters or anything and just do a getter or setter it works but to send in a string that has this doesnt? Why is this?
You should remove the () behind the Transfer method:
public class ApiViewModel : BaseViewModel
{
public bool CustomerIsChecked { get; set; }
public bool StorageIsChecked { get; set; }
public bool ArticlesIsChecked { get; set; }
public bool Transfer // <- remove ()
{
get // it should have a getter.
{
if(CustomerIsChecked == true)
{
return true;
}
return false;
}
}
public override string ToString()
{
return Transfer().ToString();
}
}
The code of Transfer could be simplified. It should return true when CustomerIsChecked is true, otherwise false.
So:
public bool Transfer
{
get => CustomerIsChecked;
}
My old answer (I didn't understood the question)
You should implement the INotifyPropertyChanged and raise he event. Too bad you need to have a full property (add a field)
Since you can only invoke an event from the class it self, you need to implement a method to raise the event in the base class.
For example:
public class BaseViewModel : INotifyPropertyChanged
{
protected void RaisePropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
public event PropertyChangedEventHandler PropertyChanged;
}
public class ApiViewModel : BaseViewModel
{
private bool _customerIsChecked;
public bool CustomerIsChecked
{
get { return _customerIsChecked; }
set
{
_customerIsChecked = value;
RaisePropertyChanged(nameof(CustomerIsChecked));
}
}
}
It's also possible to create a helper method which takes care of the property changed.
I like this style which allows the new expression-bodied member,
public class BaseViewModel : INotifyPropertyChanged
{
public bool SetField<T>(ref T field, T value, [CallerMemberName] string memberName = "")
{
if (field != null)
{
if (field.Equals(value))
return false;
}
else if (value != null)
return false;
field = value;
RaisePropertyChanged(memberName);
return true;
}
protected void RaisePropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
public event PropertyChangedEventHandler PropertyChanged;
}
public class ApiViewModel : BaseViewModel
{
private bool _customerIsChecked;
public bool CustomerIsChecked
{
get => _customerIsChecked;
set => SetField(ref _customerIsChecked, value);
}
}
Related
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));
}
}
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"));
}
}
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}"/>
I have an interface with a property:
public interface IMyInterface
{
string Test { get; set; }
}
Here is the class that implements it:
public MyClass : IMyInterface
{
private string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
RaisePropertyChanged("Test");
}
}
Public void MethodName()
{
//Logic that updates the value for Test
}
}
So far all is well, when the method gets called, Test gets updated.
I also have a ViewModel that takes this implementation of IMyInterface in its constructor.
private IMyInterface _myInterface;
public ViewModel(IMyInterface myinterface)
{
_myInterface = myinterface;
}
Is it possible for me to have a property in my ViewModel that gets updated each time the value of Test changes?
You don't necessarily need a new field - what you can do is just add another property to your ViewModel to re-expose your composed interface property:
public ViewModel
{
// ...
public string Test
{
get { return _myInterface.Test; }
set {_myInterface.Test = value }
}
}
Edit, Re raising PropertyChanged events
I would recommend that you require that IMyInterface extends INotifyPropertyChanged
public interface IMyInterface : INotifyPropertyChanged
{
string Test { get; set; }
}
Which would then be implemented by your underlying concrete class like so:
public class MyClass : IMyInterface
{
private string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
RaisePropertyChanged("Test");
}
}
private void RaisePropertyChanged(string propertyName)
{
// Null means no subscribers to the event
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
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;