Aram Gevorgyan
Aram Gevorgyan

Reputation: 2205

How do I correctly bind?

I have a class MyClass, which implements INotifyPropertyChanged, and it has some properties that must be bound in some page. In my page I have

private MyClass myclass; 

and in the page constructor I write

ContentPanel.DataContext = myclass;   

When I assign myclass to some MyClass object, which I get from some callback, nothing is shown in page.

But when I write the properties that I must change instead of MyClass class in page.cs and bind them it work correctly. Or when I give

ContentPanel.DataContext = this;

and in xaml I write

{binding this.myclass.property} 

it also works correctly.

Here is callback

 public void GetCommonInfoCallback(UserCommonInfo userCommonInfo)
    {
        CommonInfo = userCommonInfo;
    }

where UserCommonInfo is MyClass, and CommonInfo is myclass.

 private UserCommonInfo userCommonInfo ;
    public UserCommonInfo CommonInfo
    {
        get
        {
            return userCommonInfo;
        }
        set
        {
            if (userCommonInfo != value)
            {
                userCommonInfo = value;
                OnPropertyChanged("CommonInfo");
            }
        }
    }

I can't understand where is my mistake. Can you help me?

Upvotes: 0

Views: 183

Answers (1)

Visual Stuart
Visual Stuart

Reputation: 661

When you set DataContext, it is the specific instance of MyClass that is used for data binding. So after executing

ContentPanel.DataContext = myclass;

you could later execute

myclass.someProperty = "new value of someProperty";

and the data will be updated in the bound control (assuming this is not a OneTime binding, but OneWay or TwoWay binding instead).

If I understand you question correctly, you want to change the binding to use a different instance of MyClass.

myclass = new MyClass { /* ... */ }; // new instance of MyClass

At this point, the controls are still bound to the previous instance of MyClass. You can change that by updating the DataContext:

DataContext = myclass; // set context to the new MyClass instance

The second approach that you wrote, with

ContentPanel.DataContext = this;

represents a different style, where you are making the page class also serve as the data model instance for data binding.

In this case, you are not changing the data binding to use a new instance of the data model (the page instance, 'this', is not changing). IMHO, there is very valuable to separate the page and the data model, so I prefer to not use the DataContext = this approach.

Upvotes: 2

Related Questions