views:

10

answers:

1

Hello:

I'm attempting to create a simple WPF UserControl beginning with the default constructor.

public partial class MyControl : UserControl
{
  InitializeComponent();
}

Now MyControlwill require access to my database and that connection is initialized and managed externally. What is the best way to provide an external dependent resource ( in this case, a connection ) into my UserControl?

I'm familiar with dependency properties but wasn't quite sure if that was the best choice. Seems kinda like overkill. Normally, I would use constructor injection to pass in object dependencies, is that acceptable when designing a UserControl?

A: 

It depends on how you plan to use the UserControl.

If you want to be able to use XAML to define the external dependency, then I'd recommend using a Dependency Property. This will allow the property to be settable via XAML and databinding. (This, also, is the more common, more "WPF" way of doing things...)

If you're always going to construct the UserControl in code, and add it to an existing project, then using a constructor parameter is fine.

Reed Copsey
If you were to use a DependencyProperty, in my example, I would have to add default behavior during the construction of the control when the Connection hasn't been assigned and then add behavior for when the connection is actually set via the DependencyProperty later?
Matthew
@Matthew: Yes, pretty much. If you want to be able to use your class in the designer, you're going to have to do that no matter what, since the designer will require a parameterless constructor. (This is true for Visual Studio's designer as well as Blend.) That's why I mentioned you can use a constructor parameter, but only if you're going to construct the control via code.
Reed Copsey
@Reed Thanks just wanted to make sure I understood the requirements by supporting the designer and blend. Thanks for your prompt answer and comments!
Matthew