简体   繁体   English

C# WPF MVVM 2 用户控制具有相同数据上下文和 ViewModel 的视图

[英]C# WPF MVVM 2 Usercontrols views with the same data context and ViewModel

I have 2 usercontrol views, these are:我有 2 个用户控件视图,它们是:

Bmw.xaml and Audi.xaml宝马.xaml和奥迪.xaml

In both xamls I add this:在两个 xamls 中,我都添加了这个:

<UserControl
                 x:Class=TestProject.Views.Fragments.Audi
                 // The standard code generated by visual studio
                 xmlns:viewModels="clr-namespace:TestProject.ViewModels"
        <Grid>
        // XAML CODE
        </Grid>
</UserControl>

In both bmw.caml.cs and audi.xaml.cs I have this in my constructor:在 bmw.caml.cs 和 audi.xaml.cs 我的构造函数中有这个:

    public Audi()
    {
        InitializeComponent();
        this.DataContext = new BrandViewModel();
    }

And

        public BMW()
    {
        InitializeComponent();
        this.DataContext = new BrandViewModel();
    }

In the ViewModel are my functions, to keep it simple when the ViewModel is called by the Audi I want to call the function ActionAudi() and when it is called by the BMW I want to call ActionBMW().在 ViewModel 中是我的函数,为了简单起见,当奥迪调用 ViewModel 时,我想调用 function ActionAudi(),而当宝马调用它时,我想调用 ActionBMW()。

Is there a good way to know in the viewModel class whether it belongs to the audi or bmw usercontrol?在viewModel class 中是否有一个好方法可以知道它是属于audi 还是bmw usercontrol? Because depending on this there has to be executed different logic.因为根据这一点,必须执行不同的逻辑。

Thankyou in advance!先感谢您!

First, create an enum to define which brand do you have.首先,创建一个枚举来定义您拥有的品牌。 Like this像这样

public enum Brands
{
    Audi,
    BMV,
    Vinfast
}

Second, modify your ViewModel's constructor to some think like this.其次,将您的 ViewModel 的构造函数修改为这样的想法。

public BrandViewModel(Brands brand)
{
    // passing brand to a field or property
}

Finally, set your DataContext by new constructor you just created.最后,通过您刚刚创建的新构造函数设置您的 DataContext。

public Audi()
{
    InitializeComponent();
    this.DataContext = new BrandViewModel(Brands.Audi);
}

and

public BMW()
{
    InitializeComponent();
    this.DataContext = new BrandViewModel(Brands.BMW);
}

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

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