Making controls in a Silverlight/WPF User Control private

By default, when you create a User Control in Silverlight or Windows Presentation Foundation (WPF) all child controls are publicly available. This is not only bad for reusability of the control but also from the design point of view as you should always try to encapsulate the internals of your control and only make available to the outside world functionality that makes sense to them. Additionally encapsulating properties allows you to validate the input what makes your control less error prone.

Looking at the properties of a Silverlight/WPF control in the Properties Window you won’t find anything that would allow you to set the scope of a control. The Modifiers property that you might know from Windows Forms isn’t available in Silverlight/WPF. And yet there is a way to make the child controls of a User Control available only within the User Control itself.

In order to set the modifier for a control you can use the x:FieldModifier property:

<Button Content="Foo" x:FieldModifier="private" />

The above code snippet will add a button that is accessible only within the control itself.

Technorati Tags: Silverlight,WPF