How to create a binding inside a user control automatically?

I have my own custom control using DependencyProperty IsBusy

Here is how I use it:

 <Controls:myToolbar Grid.ColumnSpan="5" Mode="DataEntry" Status="{Binding State, Converter={StaticResource ViewEditingStateToToolbarStateConverter}}" IsBusy="{Binding IsBusy}"/> 

By convention, all my VMs inherit from the base VM and have the IsBusy property. So, I KNOW that this property will always be available in the virtual machine.

Now I have 4 more properties like this. Instead of adding them to XAML in all of my views, I want to know how to bind to this internal IsBusy control code, so I donโ€™t need to bind to XAML?

EDIT

In fact, I found the answer to my question: Silverlight: programmatically binding control properties

Now, my question is:

Is it correct to apply this binding in a constructor like this?

 public myToolbar() { this.DefaultStyleKey = typeof(myToolbar); var binding = new Binding("IsBusy") { Mode = BindingMode.TwoWay }; this.SetBinding(IsBusyProperty, binding); } 

Should I check if there is a XAML binding (another obligation) to this property and is not bound? It works anyway, but I wonder if this is bad for performance, smells, etc.?

How to do it in onApplyTemplate . Is this the best way?

 if (GetBindingExpression(IsBusyProperty) == null) { var binding = new Binding("IsBusy") { Mode = BindingMode.TwoWay }; this.SetBinding(IsBusyProperty, binding); } 
+3
c # silverlight binding xaml custom-controls
source share
1 answer

It would be bad if you tried to use this control with a view model that does not have the IsBusy property, but even then you will only receive a warning about debugging in the output window, nothing to worry about.

As for the binding location, the constructor is suitable if the dependency property that you are binding does not perform any actions inside its callback. But if the property of the modified callback tries to call functions such as GetTemplateChild and get the internal controls, then you should move the binding to the OnApplyTemplate functions, because only there you can be sure that the internal controls exist.

By the way, if your proxy dependency function does not have the changed callback property and is used only in the control template, for example {TemplateBinding IsBusy} , you can replace this line with {Binding IsBusy} . Something like this using bindings or data triggers:

 <ControlTemplate TargetType="{x:Type Controls:myToolbar}"> <Grid> <ContentControl x:Name="content" ... /> <ProgressBar x:name="progress" ... /> </Grid> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding IsBusy}" Value="True"> <Setter TargetName="progress" Property="Visibility" Value="Visible" /> </DataTrigger> 

The idea is simple: TemplateBinding is applied to the control's dependency properties, while Binding is applied to the properties of the DataContext or view model, and they can coexist without problems.

0
source share

All Articles