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?
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
DependencyProperty. 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.