Choub890
Choub890

Reputation: 1163

Do I need dependency properties for all basic properties on my user control?

I am currently writing my first user control which would consist of a label and a text box in a stack panel like follows:

<Grid>
    <StackPanel Orientation="Horizontal" DataContext="{Binding RelativeSource={RelativeSource Self}}">
        <Label Content="{Binding Label}" Width="60"></Label>
        <TextBox Text="{Binding TextBoxContent}" Width="60"/>
    </StackPanel>
</Grid>

This will be most useful to be in a settings page, as it will be reused for several different settings. With each of these settings, I will want to set (at a minimum) the width, height, validation rule and error template properties. As for the text itself, I have already created a dependency property both for the label and the text box (as you can see in my snippet above).

My question is this: Do I need to create a dependency property for all of the properties I just mentioned that I would like to set when I actually use my user control? This seems like redundant work (since they already exist on the text box, basically they would just redirect my user control's property to the text box's property of the same name)? This is even more work if I want to use even more properties on my text box (for example, AcceptsReturn, etc).

Upvotes: 2

Views: 80

Answers (1)

Adi Lester
Adi Lester

Reputation: 25211

The redundant work can be saved if you decide to derive from TextBox rather than UserControl - just think of your control as a "labeled textbox" and all you need to do is derive from TextBox and add the needed dependency properties to accommodate for the label. This of course would not be the case for more complex user controls, but it seems OK in your case.

The downside to this though is that you'll have to take the default control template for TextBox and work with it to add your label, which may be a bit trickier.

Either way, I recommend having a look at the Control Authoring Overview page on MSDN, which is extremely useful when writing your first controls in WPF.

Upvotes: 2

Related Questions