user2822838
user2822838

Reputation: 347

Initialising a user control in code behind not working - MVVM WPF

I am initialising a user control in code behind as the control ctor takes a MainViewModel as parameter. I also have a default ctor for this to keep XAML happy.

Now, as I understand it- XAML automatically initialises the user control using the default ctor but as I am re-initalising it in code behind - I can see that this is not working as I am getting all sorts of binding errors.

XAML:

  <childViews:SomeView x:Name="SomeViewUc"/>

XAML.cs:

public MainView(IMainViewModel mainViewModel)
{
    InitializeComponent();

    DataContext = mainViewModel;
    SomeViewUc = new SomeView(new SomeViewModel(mainViewModel)); 
}

Why is the new Initialisation not working? Any ideas?

Upvotes: 1

Views: 766

Answers (1)

Rico Suter
Rico Suter

Reputation: 11858

You cannot replace an existing control this way... you need to remove the control from the parent control and add a new one.

But have you tried something like this?

public MainView(IMainViewModel mainViewModel)
{
    InitializeComponent();

    DataContext = mainViewModel;
    SomeViewUc.DataContext = new SomeViewModel(mainViewModel); 
}

You should think about other ways to instantiate the view model, e.g. with a view model locator or directly in XAML. I wrote a blog article about view model instantiation and other best practices.

Upvotes: 2

Related Questions