markzzz
markzzz

Reputation: 47947

Why deserialize an object to DataContext loss all bindings?

On my Window, I init DataContext this way:

public partial class MainWindow : MetroWindow
{
    private ViewModelData data;
    ResourceManager? resourceManager;

    public MainWindow()
    {
        InitializeComponent();

        data = new ViewModelData();
        DataContext = data;
    }
}

And later I add some User Controls passing it to each CTOR:

var uc1 = new MyUserControl(data);
contentGrid.Children.Add(uc1);

var uc2 = new MyUserControl(data);
contentGrid.Children.Add(uc2);

(on each, I've somethings like this):

public MyUserControl(ViewModelData viewModelData)
{
    data = viewModelData;
    DataContext = data;
}

Now, during the live of the app, if on windows I do somethings like:

data.field1 = "value"

it correctly bind the value, and reflect to user control's view.

But once I do somethings like this:

data = JsonConvert.DeserializeObject<ViewModelData>(jsonContent) ?? new ViewModelData();

Taking values from external json, bind seems missing, and Views on each user controls are not updated anymore.

What's wrong? And how can I fix it? Maybe its wrong how can I deal with DataContext (pretty new on WPF).

Upvotes: -1

Views: 49

Answers (1)

Clemens
Clemens

Reputation: 128013

Do not explicitly pass the data value to the UserControls at all. Their DataContext properties will automatically inherit the value of the DataContext property of the MainWindow.

Make no DataContext assignments at all in the UserControls - neither in their XAML nor in their code behind - and create them like this:

var uc1 = new MyUserControl();
contentGrid.Children.Add(uc1);

var uc2 = new MyUserControl();
contentGrid.Children.Add(uc2);

When you later assign a new value to the MainWindow's DataContext, the UserControls will also get this value - automatically by dependency property value inheritance.

DataContext = JsonConvert.DeserializeObject<ViewModelData>(jsonContent)
            ?? new ViewModelData();

Upvotes: 2

Related Questions