Mathivanan KP
Mathivanan KP

Reputation: 2044

WPF DataContext issue with datacontext object

I have created a simple sample with datacontext. Please get the sample from here : source I understand that the uses of DataContext is

  1. If the user change any content in UI, it should be updated in the back end datacontext class without any additional work.
  2. If we make any change in back end datacontext object, it should be updated in UI without any additional work.

In my sample,

  1. If I click "click" button, the textbox value gets updated. - pass

  2. If I click "update" button, the textbox value gets updated. - pass

  3. If I click "clear" button, the textbox value not updated. - fail

  4. After clicked "clear" button, If "click" or "update" button is clicked the textbox value not updated. - fail

Am I doing anything wrong? If yes, how can I initialize some value in the textbox in constructor, and after that if the user make changes, the datacontext object values need to be updated. If I update any value in code behind, the values need to updated in UI. Also if I click "clear" button all the textbox values need to be cleared. After that if user enter value again, the object need to update. How can I achieve it? Please help.

Note: In my sample I have commented some lines. In that i have casted the datacontext to the model class every time and changed it. Its working fine. Do i need to use that method to update values run time. Changing values in object will not update in UI?

Upvotes: 0

Views: 54

Answers (1)

Lupu Silviu
Lupu Silviu

Reputation: 1165

The problem is that you consider the variable 'dc' linked to the DataContext, but that is not the case. To fix your code simply set the DataContext again after you change the 'dc' variable.

 private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        dc = new Journal();
        myPanel.DataContext = dc;
        //myPanel.DataContext = new Journal();
    }

Upvotes: 2

Related Questions