How Can I bind DataContext to a Generic ViewModel in XAML?

前端 未结 4 1804
夕颜
夕颜 2021-02-20 09:17

Suppose we have a generic View model like this:

public class MyViewModel : INotifyPropertyChanged where T : Class1
{
    private T _objectModel;
    pub         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 10:11

    If your ViewModel is derived from a base class, let's say NonGenericViewModel then you can assign in code behind an object of type NonGenericViewModel to the DataContext. Using this way you still have the benefits of generics and the data binding will also work because the bindings will be made during runtime, no matter what type of object you assign to DataContext as long as it has properties, collections, etc required by your xaml controls.

    BaseViewModel : NonGenericViewModel { ... }
    
    NonGenericViewModel : INotifyPropertyChanged { ... }
    

    And in code behind, in the ctor of your xaml.cs:

    NonGenericViewModel nonGenVM = new BaseViewModel();
    this.DataContext = nonGenVM;
    

    Even this is correct and working:

    this.DataContext = new BaseViewModel();
    

    It depends if you need or not the class NonGenericViewModel in other places.

提交回复
热议问题