Search code examples
c#wpfmvvm

WPF MVVM 2 Usercontrols views with the same data context and ViewModel


I have 2 usercontrol views, these are: Bmw.xaml and Audi.xaml.

In both xamls I add this:

<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:

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().

Is there a good way to know in the viewModel class whether it belongs to the audi or bmw usercontrol? Because depending on this there has to be executed different logic.

Thank you in advance!


Solution

  • First, create an enum to define which brand do you have. Like this

    public enum Brands
    {
        Audi,
        BMW,
        Vinfast
    }
    

    Second, modify your ViewModel's constructor to some think like this.

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

    Finally, set your DataContext by new constructor you just created.

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

    and

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