Creating UserControls with ViewModels in WPF

2019-02-19 12:16发布

问题:

do you think is a good practise to create a UserControl already with a ViewModel and deploy both together? This way the UserControl will be binded to the ViewModel from stock.

Looks as a good idea to me but I never saw such a thing.

Thanks.

回答1:

The one thing you should be careful of with this approach is that you want to keep your datacontext open and available for binding to in controls where you are using this control.

If you block the data context it'll make it so any bindings you do to the control later will have to have a source specified.



回答2:

I personally see nothing bad in this idea. For a sufficiently complex UserControl, a ViewModel is anyway needed. I would however make it (VM) as extensible as possible.

Indeed, I've seen some VMs shipped together with controls -- in Swing (Java). For example, TableModel serves indeed as a kind of VM for JTable. [But without real bindings Swing's VMs are quite weak.]