0

How can I use the properties of the controls that are inside a user control without having to use DependencyProperty?

Since, if for example I want to use all the properties of a button, I would have to declare all these?

And if there is another way without user control and it is the correct one, I would appreciate it if you answered it. (Google translator, sorry)

UserControl:

<UserControl x:Class="UserControls.UserControl01"
                 ...
                 >
        <Grid>
            <Button x:Name="uc_btn" />
            <TextBox x:Name="uc_txt"  />
            <DataGrid x:Name="uc_dtg"  />
        </Grid>
    </UserControl>

Code using the UserControl:

<Window x:Class="UserControls.wnd02"
        ...
        >
    <Grid>
        <local:UserControl01 uc_btn.Background="Red" uc_txt.Margin="10" uc_dtg.BorderThickness="5" Margin="90" />

        <local:UserControl01 uc_btn.Background="Green" uc_txt.Margin="25" uc_dtg.BorderThickness="20" Margin="5" />
    </Grid>
</Window>
tlh
  • 1
  • 1

1 Answers1

0

It is not usual to do what you are asking.

Let's consider a usercontrol which is intended to work as if it is one single control. For example a time picker. This contains two sliders which increase/decrease hour and minute. You can also overtype in the hour and minute textboxes and there's a : between the two textboxes.

This usercontrol is all about the one property though. Time. You don't care what the minutes background is externally. If this changes it's internal to the usercontrol.

In this scenario you'd usually add a TimeSpan dependency property to the usercontrol and this is the only thing anything external to it uses.

Pretty much all commercial WPF development uses the MVVM pattern and that TimeSpan would be bound to a property in the parent view's viewmodel.

That's one scenario.

Another is where a usercontrol encapsulates a bunch of UI which is then re-usable.

Styling has scope so when you apply a style to say a Button in a window then that would apply to any Buttons in a usercontrol within it. Setting their properties.

There are also certain dependency properties marked as "inherits" whose values propogate down the visual tree.

One such is DataContext and it is this which most teams would use to deal with properties within a usercontrol.

Using MVVM there would be a MainWindowViewModel.

That would have (say ) a ChildUserControlViewModel property. That would be associated with usercontrol using a datatemplate specified datatype.

You'd then bind properties of whatever is in a usercontrol to properties of ChildUserControlViewModel or properties of MainWindowViewModel using RelativeSource binding.

ViewModel first is a common navigation and composition pattern for WPF. You should be able to find numerous blogs explain it better than I can in a SO post.

Here's one:

https://social.technet.microsoft.com/wiki/contents/articles/30898.simple-navigation-technique-in-wpf-using-mvvm.aspx

Andy
  • 11,864
  • 2
  • 17
  • 20