wpfxamlbinding

Can you set relative source of all properties within a control instead of setting it inline on property?


I am starting to get a hang of all this binding and WPF stuff. One thing I am stuck on is the following. I have a User control here and I want to bind the properties (custom dependency properties) with data from other classes, or in this case the same one. I am doing this simply because I have different user controls for different situations but using the same user control.

Everything currently works as such. Also if I do not do any binding the dependency properties work just fine. Just seeing if I can come up with a cleaner solution so I do not have to keep typing this relative source every time.

Calibration Control is a Custom User Control and the Calibration Subpage is set to local but it will be other classes as well.

<components:CalibrationControl
    Grid.Row="0"
    BarMax="{Binding ViewModel.Throttle1.BarMax, RelativeSource={RelativeSource AncestorType=local:CalibrationSubpage}}"
    BarMin="{Binding ViewModel.Throttle1.BarMin, RelativeSource={RelativeSource AncestorType=local:CalibrationSubpage}}"
    BarValue="{Binding ViewModel.Throttle1.BarValue,RelativeSource={RelativeSource AncestorType=local:CalibrationSubpage}}"
    DeadZone="0"
    IsEnabled="True"
    Panel="{Binding ViewModel.Throttle1.Panel,RelativeSource={RelativeSource AncestorType=local:CalibrationSubpage}}" />```


I would like to know if I can make an easier way to do this.

Solution

  • you can narrow down control's DataContext and then bind each property declaring only Path:

    <components:CalibrationControl
        Grid.Row="0"
        DataContext="{Binding ViewModel.Throttle1, RelativeSource={RelativeSource AncestorType=local:CalibrationSubpage}}"
        BarMax="{Binding BarMax}"
        BarMin="{Binding BarMin}"
        BarValue="{Binding BarValue}"
        DeadZone="0"
        IsEnabled="True"
        Panel="{Binding Panel}" />