karollo
karollo

Reputation: 595

Binding to an object

I have a simple Person model:

public class Person
{       
    public string FirstName { get; set; }
    public DateTime LastUpdated { get; set; }
}

Lets say that I have a View that has a TextBox, which is binded to LastUpdated field:

<TextBox Grid.Column="1" Margin="5" Text="{Binding Person.FirstName}"/>

Now I need to implement PropertyChanged somehow. Let's use Prism Snippet. What I need is to perform SetProperty on a Person class:

private Person person;
public Person Person
{
  get { return person; }
  set { SetProperty(ref person, value); }  
}

and NOT on the field LastUpdated in Person class:

private DateTime? lastUpdated;
public DateTime? LastUpdated
{
   get { return lastUpdated; }
   set { SetProperty(ref lastUpdated, value); }
}

This is not the matter of dependencies in the model. I got the model through DataContract ( WCF service ) so I cannot changed it. So is there a way to observe a class for changes and bind class field to some UI control.

Upvotes: 0

Views: 54

Answers (2)

mm8
mm8

Reputation: 169200

So is there a way to observe a class for changes and bind class field to some UI control.

No. You need to raise the PropertyChanged event for the object of the property that you are actually binding to.

If you get the Person object from some third-party service for which you cannot modify the code to raise the PropertyChanged event in the setter of the FirstName property, you should not bind to these objects.

Instead you should create your own view model class and bind to this one. The view model can simply wrap the WCF class, e.g.:

public class PersonViewModel
{
    private readonly Person _person;
    public PersonViewModel(Person person)
    {
        _person = person;
    }

    public string FirstName
    {
        get { return _person.FirstName; }
        set { _person.FirstName = value; RaisePropertyChanged(); }
    }
}

Upvotes: 1

Ronald Zarīts
Ronald Zarīts

Reputation: 12699

If you're using Prism, then you likely are using the MVVM pattern. If so, then the one approach is using the view model for binding. Instead of exposing Person as a property, expose the individual properties you want to bind against - FirstName and LastUpdated:

  • Create a property on the view model that forwards calls to your model.
  • Bind your view to the view model property.
  • You can freely implement your change notifications in the view model.

Upvotes: 1

Related Questions