CalciumFramework / Samples

Samples demonstrate how to use some of the features of Codon.
3 stars 2 forks source link

Raise PropertyChanged for derived properties #4

Closed abrasat closed 7 years ago

abrasat commented 7 years ago

Which is the best approach to manually raise a PropertyChanged for a derived property (a property that has only a getter and which changes only if some other properties change). I used earlier MvvmLight, they had an overload of the Set() method taking a "property" Expression as additional parameter, and then extracting "behind the scenes" the property name from the Expression containing the property variable. Is this also somehow possible with Codon ? I would like to avoid using strings to pass the property names (as I said, this is needed only for derived properties for which OnPropertyChanged should be called manually, as in this case it is not possible to use [CallerMemberName] for getting the property name).

DVaughan commented 7 years ago

If wish to call that from a view-model, just call: OnPropertyChanged(nameof(MyProperty));

Using reflection for property name discovery has been superseded with the nameof expression.

DVaughan commented 7 years ago

By the way, the Extras package includes the Codon.UIModel.ComputerObservable class that allows you to define properties that update based on other properties. It may be overkill for what you're trying to do. But, I thought I'd mention it anyway.

Here's some of the documentation:

It is used to wrap a value and provides change notification for bindings without adding plumbing to a viewmodel. This class allows you to provide an expression that is parsed to locate associated objects that implement INotifyPropertyChanged. When a change notification is received from any such objects, the value of the expression is recomputed.

class MainWindowViewModel
{
    public MainWindowViewModel()
    {
        fullName = new ComputedObservable<string>(() => FirstName.Value + " " + ToUpper(LastName.Value));
     }
}

There's a post from 2012 over on my blog

abrasat commented 7 years ago

Thank you, that is I was looking for. Do the "base" properties (FirstName, LastName) the ComputedObservable property (FullName) is based on have to be defined as Observable<>, or not necessarily ? Can these properties also be defined as plain strings, having a setter which would at value change automatically trigger the re-calculation of the Computed Observable property ?

DVaughan commented 7 years ago

Yes, but when there's a limitation in that you need to refer to any properties via an variable. For example:

var vm = this;
FullName = new ComputedObservable<string>(() => vm.FirstName + " " + vm.LastName);

I need to do some work on the expression deconstruction to deduce the owner when not specified. I've attached a sample for you: ObservablesTest.zip