how to load wpf usercontrol in MVVM pattern

前端 未结 6 1741
刺人心
刺人心 2021-02-06 12:36

I\'m creating a wpf user control which is in mvvm pattern. So we have : view(with no code in codebehind file), viewmodel,model,dataaccess files.

I have MainWindo

6条回答
  •  鱼传尺愫
    2021-02-06 13:07

    I know this is an old, answered question, but I have a different approach. I like to make implicit relationships in the App.xaml file:

    
        
            
        
    
    

    With this, there is no need to set a DataContext anywhere.

    UPDATE >>>

    In response to @Vignesh Natraj's request, here is a fuller explanation:

    Once you have set up the DataTemplate in a Resources element, you can display the KioskView in this example by adding an instance of the KioskViewModel anywhere in your XAML. This could be filling the MainWindow, or just inside a particular section of the screen. You could also host multiple instances of the KioskViewModel in a ListBox and it will generate multiple KioskView instances.

    You can add an instance of the KioskViewModel to your XAML in a couple of ways, depending on your requirements. One way is to declare the XML namespace for the project that contains the KioskViewModel.cs file and simply add an instance of it in a ContentControl to the page where you want your view to appear. For example, if you had a UserControl called MainView and the KioskViewModel.cs file was in a Kiosk.ViewModels namespace, you could use basic XAML like this:

    
        
            
            
                
            
        
        
    
    

    I prefer to use the MVVM design pattern with WPF, so I would have a base view model class providing useful functionality such as implementing the essential INotifyPropertyChanged interface. I then have a property called ViewModel in the main (top level) view model of type BaseViewModel. This provides me with a nice way to change the ViewModel property to any view model that has derived from BaseViewModel and therefore to be able to change the associated view from the view model.

    For example, in the MainViewModel.cs class that is bound to MainView there is a field and relating property:

    private BaseViewModel viewModel = new KioskViewModel();
    public BaseViewModel ViewModel
    {
        get { return viewModel; }
        set { viewModel = value; NotifyPropertyChanged("ViewModel"); }
    }
    

    As you can see, it starts off as a KioskViewModel instance, but can be changed to any other view at any time in response to user interaction. For this setup, the XAML is very similar, but instead of declaring an instance of the view model in the Resources element, we bind to the property in the MainViewModel:

    
        
    
    

    Note that for this example, we would need to declare two (or more to make this approach useful) DataTemplates in the App.xaml file:

    
        
            
        
        
            
        
    
    

提交回复
热议问题