Preferred method for binding in MVVM, Data Template in Resources file or just DataContext in View itself?

后端 未结 2 1566
执笔经年
执笔经年 2021-02-06 02:14

This one has got me stumped as I THOUGHT I looked at everything but I must be missing something. I have went off the traditional MVVM pattern from the MSDN magazine:

h

2条回答
  •  一生所求
    2021-02-06 02:36

    If you want to use implicit DataTemplates you have to use the view-model-first approach, you however add a view to your DockPanel without a view-model as its context. If you simply add the respective view-model (to a ContentControl or ItemsControl), the view will be created automatically from the DataTemplate with the view-model as its DataContext.

    e.g.

    
    

    ic.Items.Add(new DataBoundMVVMChartViewModel());
    

    I personally prefer this over view-first (e.g. adding a view which then assigns its own DataContext), because you usually want references to the view-models, the view is only secondary and manipulated indirectly by interacting with the view-model.

提交回复
热议问题