How to report that custom (added) Calculated Prope

2019-08-11 05:43发布

问题:

First, I apologize for my low level English writing.

I use Entity Framework and data-binding in WPF MVVM project. I would like to know what is the best way to do data binding to added calculated property of EntityObject which is generated with Entity Framework.

For example:

partial class Person
{
    partial string Name...

    partial string Surname...

    public string FullName
    {
        get { return Name + Surname; }
    }
}

And then in XAML something like ...Text="{Binding FullName, Mode=Twoway}"

At this point my GUI doesn't know when property FullName is changed... how can I notify it? I've tried with ReportPropertyChanged but it return's an error...

Also, I wonder what is the best way to implement binding when one binding depends on more properties...calculated properties or value converters or something different?

回答1:

You could subscribe to the PropertyChanged event in the constructor and if the property name matches either of the two source properties, raise the event for the calculated one.

public Person()
{
    this.PropertyChanged += (o, e) =>
        {
            if (e.PropertyName == "Name" || e.PropertyName == "Surname") OnPropertyChanged("FullName");
        };
}


回答2:

I am not sure if you are looking for this kind of thing:

public string FullName
{
    get { return Name + Surname; }
    set 
    {
        // You should do some validation while and before splitting the value
        this.Name = value.Split(new []{' '})[0];
        this.Surname = value.Split(new []{' '})[1];
    }
}