Create custom control with properties

Topics: Questions
Sep 14, 2012 at 9:10 AM


I have a problem finding the right concept as how to create a certain usercontrol/custom control with its own properties supporting databinding and a clean MVVM approach.

What I want to do:
A usercontrol "SelectionBoxControl" that works similar to a DropDownBox. A text is displayed and an Id is databound to the containing viewmodel. Next to it a button that brings up an selection dialog. After selecting a value in the dialog the window is closed and the Text and Id are updated in the usercontrol and therefore in the viewmodel.
The usercontrol must not handle the dialog. A function must be set on the usercontrol that receives - when called from the usercontrols viewmodel - a new Id and Text (and internally calls a selection dialog).

The syntax could be like this

<DataWindow Name="CustomerWindow">
  <my:SelectionBoxControl Text="{Binding CustomerName}" Id="{Binding CustomerId}" SelectFunction="{Binding SelectNewCustomerDelegate}" DataContext="???"/>

The CustomerViewModel would contain e.g.:
string CustomerName
long CustomerId
Func<Tuple<string,long>> SelectNewCustomerDelegate

How do I have to create the custom control catel-like?

I can create a UserControl and an corresponding ViewModel. If I create DependencyProperties in the codebehind of SelectionBoxControl I can access them as outlined above, but how to access these values from the SelectionBoxViewModel?
If I add those properties to the SelectionBoxViewModel instead I cannot set them within CustomerWindow.
What to set the DataContext to?

I have already a "knot in my head" (literally german translation) as to how these 4 entites (CustomerWindow, CustomerUserControl, SelectionBoxControl and SelectionBoxViewModel) should work together. I'm lost.

Thanks for any help,

Sep 14, 2012 at 3:08 PM

You must ask yourself: is this a user control or a custom control. This sounds a lot like a custom control (but I might be wrong). If it is a custom control, don't go for MVVM. There is no requirement for separate of concerns. So, just create a simple control with dependency properties.