开发者

WPF - Should a user control be supplied with a ViewModel

开发者 https://www.devze.com 2022-12-14 17:35 出处:网络
I\'m about to use a user control developed by a different t开发者_如何学JAVAeam (in the same company) and for the app we\'re developing we\'re attempting to describe all the data binding in XAML.

I'm about to use a user control developed by a different t开发者_如何学JAVAeam (in the same company) and for the app we're developing we're attempting to describe all the data binding in XAML.

Now if I use a third party user control should I expect them to supply a basic ViewModel with hooks for my code or should I expect to write code to bind the user control to a ViewModel of my choice?

Cheers

AWC


It depends on the scope of the UserControl. If it is particular to the application and is unlikely to be useful elsewhere then yes, a public ViewModel should probably be supplied.

However, a public ViewModel is likely to be less useful where the control is expected to be re-usable. The control may use a ViewModel internally, but this should be kept private. Then the host application uses the control in a similar way to any other WPF control, and creates it's own view model to tie the control to the application.

In essence, a ViewModel is usually particular to an application - it is tailored specifically to the needs of that application. Whereas general purpose controls expose properties and events that allow them to be used in any application.


Write the controller class yourself. A reusable control should not know which type of data it's working with, unless it's specifically written for it. But then it wouldn't be very reusable :)


The control is supplied as a self contained unit. If it has it's own viewmodel internally which has hooks exposed that is all great, but to you it doesn't matter because you cannot manipulate it directly.

If you really feel the need then you should write your own viewmodel for the supplied control, as this abstracts the UI (the supplied control) from the controller (your code). That is one of the purposes of the pattern - to separate concerns, so you can swap out any part with minimal effect on the remaining parts.

But having said that, not every control is going to need its own viewmodel, instead you would use the supplied control as part of a larger user control, and write a viewmodel for that larger control.

0

精彩评论

暂无评论...
验证码 换一张
取 消