简体   繁体   English

在无法运行的代码中初始化用户控件-MVVM WPF

[英]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. 我正在后面的代码中初始化用户控件,因为控件ctor将MainViewModel作为参数。 I also have a default ctor for this to keep XAML happy. 我也为此有一个默认的ctor,以使XAML保持满意。

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使用默认的ctor自动初始化用户控件,但是当我在后面的代码中重新初始化它时-我可以看到这是行不通的,因为我遇到了各种各样的绑定错误。

XAML: XAML:

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

XAML.cs: XAML.cs:

public MainView(IMainViewModel mainViewModel)
{
    InitializeComponent();

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

Why is the new Initialisation not working? 为什么新的初始化不起作用? Any ideas? 有任何想法吗?

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, eg with a view model locator or directly in XAML. 您应该考虑其他方法来实例化视图模型,例如,使用视图模型定位器或直接在XAML中。 I wrote a blog article about view model instantiation and other best practices. 我写了一篇有关视图模型实例化和其他最佳实践的博客文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM