Implementing RaiseCanExecuteChanged method inside setter of a class object - c#

I am still not sure if my approach is correct, but in an attempt to implement the MVVM pattern, I have created a model class 'Test' in the following way:
public class Test : BindableBase
{
private int testNumber;
public int TestNumber
{
get { return testNumber; }
set { SetProperty(ref testNumber, value) }
}
...
}
Then I created an instance of this class in my ViewModel:
class ViewModel : BindableBase
{
private Test testVM;
public Test TestVM
{
get { return testVM; }
set { SetProperty(ref testVM, value); }
}
...
And in the XAML code of the View I bind all the properties of the Test class through the TestVM property. Although this works fine, I ran into a problem when trying to implement a DelegateCommad.
public DelegateCommand StartTestCommand { get; private set; }
So far, when implementing DelegateCommands, if I want to trigger the CanExecute method when a property has changed, I include DelegateCommand.RaiseCanExecuteChanged() inside the property's setter. Like so:
...
private bool duringTest;
public bool DuringTest
{
get { return duringTest; }
set
{
SetProperty(ref duringTest, value);
StartTestCommand.RaiseCanExecuteChanged();
}
}
...
This works fine for properties declared in the ViewModel, but when using the same approach for the Test properties, this no longer works.
...
private Test testVM;
public Test TestVM
{
get { return testVM; }
set
{
SetProperty(ref testVM, value);
StartTestCommand.RaiseCanExecuteChanged();
}
}
}
I would expect that every time a property from TestVM was changed, the setter would be called, but instead the model is updated directly.
What am I doing wrong? What is the correct approach when using a Model object in the ViewModel?

Changing a property value of an object doesn't change the object's reference.
Declaring this
public Test TestVM
{
get { return testVM; }
set
{
SetProperty(ref testVM, value);
StartTestCommand.RaiseCanExecuteChanged();
}
}
you are basically telling the compiler: when the reference to the TestVM object is changed (even to the same value), update the StartTestCommand's state.
But obviously you don't change the reference to that object once you assigned it.
If you want to update the commands in your parent view-model (ViewModel) when some child view-model's (Test) properties change, you can use the PropertyChanged event:
public Test TestVM
{
get { return testVM; }
set
{
Test oldValue = testVM;
if (SetProperty(ref testVM, value))
{
if (oldValue != null)
{
oldValue.PropertyChanged -= TestPropertyChanged;
}
if (testVM!= null)
{
testVM.PropertyChanged += TestPropertyChanged;
}
}
}
}
void TestPropertyChanged(object sender, PropertyChangedEventArgs e)
{
// filter if necessary
if (e.PropertyName == "...")
{
StartTestCommand.RaiseCanExecuteChanged();
}
}

Related

Binding to count on observable collection of subclass

I do have a WPF binding question here.
Following Setup:
I do have a class (ActionService) having a name and a ObservableCollection of subitems (also a class named Step). A Step has a flag that shows if the Step is allready done (IsDone).
I bind a form to the ActionService and display all kind of things.
Everything works as aspected and i have just the essential parts in my snippet.
Now I need one more thing that i can not get work. I want the ActionService to know by binding how many of its Steps are open (IsDone == false). I you open a childform with one of the steps and change the IsDone-State, the mother form should get the new count on the fly.
And I'm to dumb to get a correct solution on the way ;-)
Thanks for your help or a best practise.
public class ActionService : BaseObject
{
public ActionService()
{
}
private String name;
public String Name
{
get { return this.name; }
set
{
this.name = value;
raisePropertyChanged("Name");
}
}
public ObservableCollection<Step> actionsteps;
public ObservableCollection<Step> ActionSteps
{
get { return this.actionsteps; }
set
{
this.actionsteps = value;
raisePropertyChanged("ActionSteps");
}
}
}
public class Step : BaseObject
{
public Step()
{
}
private String description;
public String Description
{
get { return this.description; }
set
{
this.description = value;
raisePropertyChanged("Description");
}
}
private Boolean isdone;
public Boolean IsDone
{
get { return this.isdone; }
set
{
this.isdone = value;
raisePropertyChanged("IsDone");
}
}
}
public class BaseObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void raisePropertyChanged(String parPropertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(parPropertyName));
}
}
}
You can create a new property in your ActionService class:
public bool IsDone
{
get
{
return ActionSteps.Count(x => x.IsDone) == ActionSteps.Count;
}
}
If the count of Steps in the ActionSteps list where the IsDone property is true is equal to the number of Steps in the ActionSteps list, then return true, else, return false.
To subscribe to the Steps property changed event, when you add an item to the collection, you simply need to subscribe to the PropertyChanged event:
//Create the item and subscribe to propertychanged.
Step item = new Step();
item.PropertyChanged += item_PropertyChanged;
//Add the item to the list.
ActionSteps.Add(item);
And your method will look like this:
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsDone")
raisePropertyChanged("IsDone");
}

NotifyPropertyChanged through code

I have a class that contains two other objects.
A variable in the first object bind to WPF element, call it X.
A similar variable in the other object.
I want that when the PropertyChanged event happens, it will change the variable in the second object.
Here is the code that does not work for me:
The class that contains the variables: (I had register to property changed event)
private Class1 _var1;
public Class1 Var1
{
get { return _var1; }
set
{
_var1= value;
if (_var1!= null)
_var1.PropertyChanged += new PropertyChangedEventHandler(_var1_PropertyChanged);
else
_var1.PropertyChanged -= new PropertyChangedEventHandler(_var1_PropertyChanged);
}
}
void _var1_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(e.PropertyName=="X")
Var2.X= Var1.X;
}
private Class2 _var2;
public Class2 Var2
{
get { return _var2; }
set { _var2= value; }
}
Class 1:
private int _x;
public int X
{
get { return _x; }
set
{
if (_x!= value)
{
_x= value;
NotifyPropertyChanged("X");
}
}
}
class 2:
public int X { get; set; }
PropertyChanged work in class 1 but he did not come to an event I created in a class that contains the two variables, why?
I'm not sure I understand exactly what you mean, but if I had a class with 2 variables that I wanted to change together, I would try the following:
First, define some SetAndNotify method or you'll get a headache from the PropertyChanged events:
public void SetAndNotify<T>(ref T field, T value, Expression<Func<T>> exp)
{
if (!Equals(field, value))
{
field = value;
OnPropertyChanged(exp);
}
}
Add it to some base class that will handle this event.
Second, in your setter for Var1 you register for the change event and not set anything, is that on purpose?
Third and last, there's no problem with changing more than one property in a setter, but make sure it's the public property that you change:
private SomeType privateVar1;
public SomeType PublicVar1
{
get { return privateVar1; }
set
{
SetAndNotify(ref privateVar1, value, () => PublicVar1);
MyOtherPublicVar = someNewValue; // this will activate the property's setter.
}
}
I hope this helps. If not, please try to clarify your question.

Binding label content to a value in nested class not in Datacontext

My view (InformationView) Binded to InformationViewModel and I use a nested class to maintain current Bank
My nested class :
public class MainController : NotificationObject
{
public MainController()
{
Initialize();
}
private void Initialize()
{
// TODO implement
}
public static MainController Instance
{
get { return Nested.instance; }
}
private BankModel _currentBank;
public BankModel CurrentBank
{
get { return _currentBank; }
set
{
if (_currentBank== value)
{
return;
}
_currentBank= value;
RaisePropertyChanged(() => CurrentBank);
}
}
private class Nested
{
static Nested()
{
}
internal static readonly MainController instance = new MainController();
}
}
My BankModel :
private string _name ="test";
public string Name
{
get
{
return _name;
}
set
{
if (_name == value)
{
return;
}
_name= value;
RaisePropertyChanged(()=>Name);
}
}
My XAML
xmlns:Controller="clr-namespace:MyProject.Controller"
/****/
<Label Content="{Binding Controller:MainController.CurrentBank.Name}"/>
first I can't see the "test" in my label and if I execute I change this value and always my label is empty, how I do this with the correct approach
You need to use a combination of "Path" and "Source" in your binding declaration. You also need to alert the binding engine to the fact that you're accessing static members.
<Label Content="{Binding Source={x:Static Controller:MainController.Instance}, Path=CurrentBank.Name}" />

Get/Set for a Private Static Collection?

I've defined a class with the following property:
private ObservableCollection<Job> allJobs;
Access is defined as follows:
public ObservableCollection<Job> AllJobs
{
get
{
return this.allJobs;
}
set
{
this.allJobs = value;
}
}
The get set works fine when I assign a whole ObservableCollection to the property, the set works fine for retrieving it obviously. But why have I lost all the methods that normally allow me to 'Add' (i.e. add 1 job to the collection)?
At the moment I'm having to create a temporary collection to populate to then assign to the allJobs property and I shouldn't have to.
Any ideas??
What do you mean with 'lost methods'? Have you tried AllJobs.Add()? The following code works for me:
void Main()
{
AllJobs = new ObservableCollection<Job>();
AllJobs.Add(new Job());
}
public class Job { }
private ObservableCollection<Job> allJobs;
public ObservableCollection<Job> AllJobs
{
get
{
return this.allJobs;
}
set
{
this.allJobs = value;
}
}
EDIT:
Based on your comment I've amended my code as follows but everything still works for me, I have noticed however that you don't seen to initialise the allJobs collection anywhere.
void Main()
{
PresentationManager.Instance.AllJobs.Add(new Job());
}
public class Job { }
sealed class PresentationManager
{
public static readonly PresentationManager Instance = new PresentationManager();
private PresentationManager()
{
allJobs = new ObservableCollection<Job>();
}
private ObservableCollection<Job> allJobs;
public ObservableCollection<Job> AllJobs
{
get { return this.allJobs; }
set { this.allJobs = value; }
}
}
Normally you wouldn't want a setter for such a property, as you would lose all events bound to the ObservableCollection when the setter is used.
public ObservableCollection<Job> AllJobs { get; private set; }

How to use INotifyPropertyChanged on a property in a class within a class..?

My issue seems to be "scope", though I'm not certain that's the right terminology. I want to notify a read-only list to re-evaluate itself when a property within a custom object is set. I believe it is simply not aware of it's existence. Maybe there is an easy way around this I cannot think of, but I'm drawing a blank.
I find this hard to put into words, so here's simplified code with my comments on what I expect to happen.
Properties within object in which I am databinding to:
private CvarAspectRatios _aspectRatio = new CvarAspectRatios("none", GetRatio());
public CvarAspectRatios AspectRatio
{
get { return _aspectRatio; }
set
{ // This setter never gets hit since I bind to this
if (value != null) // object's 'Value' property now.
{
_aspectRatio = value;
NotifyPropertyChanged("AspectRatio");
NotifyPropertyChanged("ResolutionList"); // I want to inform ResolutionList
} // that it needs to repopulate based
} // on this property: AspectRatio
}
private ResolutionCollection _resolutionList = ResolutionCollection.GetResolutionCollection();
public ResolutionCollection ResolutionList
{
get
{
ResolutionCollection list = new ResolutionCollection();
if (AspectRatio != null && AspectRatio.Value != null)
{
foreach (Resolutions res in _resolutionList.Where(i => i.Compatibility == AspectRatio.Value.Compatibility))
{
list.Add(res);
}
return list;
}
return _resolutionList;
}
}
CvarAspectRatios Class:
public class CVarAspectRatios : INotifyPropertyChanged
{
private string _defaultValue;
public string DefaultValue
{
get { return _defaultValue; }
set { _defaultValue = value; NotifyPropertyChanged("DefaultValue"); }
}
private AspectRatios _value;
public AspectRatios Value
{
get { return _value; }
set
{
_value = value;
NotifyPropertyChanged("Value");
NotifyPropertyChanged("ResolutionList"); // This value gets set, and I'd like for ResolutionList to update
} // but it cannot find ResolutionList. No errors or anything. Just
} // no update.
public AspectRatios() { }
public AspectRatios(string defaultValue, AspectRatios val)
{
DefaultValue = defaultValue;
Value = val;
}
// Implementation of INotifyPropertyChanged snipped out here
}
What do you folks think? If you'd like a sample application I can whip one up.
Since CVarAspectRatios implements INotifyPropertyChanged, you can have the viewmodel class subscribe to the PropertyChanged event for the AspectRatio.
public class YourViewModel
{
public YourViewModel()
{
AspectRatio.PropertyChanged += AspectRatio_PropertyChanged;
}
void AspectRatio_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Value")
NotifyPropertyChanged("ResolutionList");
}
}
Just bear in mind that if you discard that AspectRatio object (if the object reference changes and not just the value property of that object), you should unsubscribe from the event on the discarded one.
To just transform your existing code into something which should work:
private CvarAspectRatios _aspectRatio; //No field initialization because that would not attach event handler, you could do it though and take care of the handler alone in the ctor
public CvarAspectRatios AspectRatio
{
get { return _aspectRatio; }
set
{
if (_aspectRatio != value) // WTH # "value != null"
{
_aspectRatio.PropertyChanged -= AspectRatio_PropertyChanged;
_aspectRatio = value;
_aspectRatio.PropertyChanged += new PropertyChangedEventHandler(AspectRatio_PropertyChanged);
NotifyPropertyChanged("AspectRatio");
}
}
}
void AspectRatio_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Value")
{
NotifyPropertyChanged("ResolutionList");
}
}
Why don't you factor out re-populating ResolutionList into a separate private method which gets called from the setter of AspectRatios?
If a list needs to update based on a changed property, the list (or a list manager object, for better encapsulation) would normally need to subscribe to the PropertyChanged event of the object hosting the property. If the list is itself a property of the same object, as in this case, it would be simpler and leaner for the property's setter to call a method that updates the list.

Categories

Resources