I'm learning C#, and I just came across events, I'm reading the following code:
class ACommand : ICommand
{
public ACommand()
{
Model.Duck.Weight.PropertyChanged += (sender, args) =>
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, new EventArgs());
}
};
}
public bool CanExecute(object parameter)
{
//some code
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
//some code
}
}
I understand most of it, but what I don't really get is the part:
Model.Duck.Weight.PropertyChanged += (sender, args) =>
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, new EventArgs());
}
};
- Does this code just tells the program that whenever the ducks wieght changes, it should execute CanExecute methode, and warn everybody who is bound on this command?
- Also, when the duck changes, should I unsubscribe from the old duck and subscribe to the new duck? Because If I don't unsubscribe and only add a subscription to the new duck, the old one will still get notified when something changes,or am I wrong? (Can anybody show me how I unsubscribe from the old duck, when the Model.Duck changes? Thank you.
PropertyChanged is the name of the event triggered by Model.Duck.Weight. With += you're adding a receiver to the event. You could add an existing function here, like Windows Forms would do:
with
But in your case, instead of giving a concrete function, an anonymous function is added as a handler to the PropertyChanged event:
Inside the function (where my //do something is), you fire your own event, CanExecuteChanged. The check for null makes sure, someone else has added an event handler to your event and if so, you just fire it.
PS: Unsubscribing works exactly the other way around: