Posts tagged ‘Code Behind’

C# Silverlight: Codebehind Binding Between Two Controls Example

Here is a quick example of binding between two controls on the same xaml page. I have provided both ways of doing the binding the first in xaml and the second in the code behind. The first example is the most common method of binding in xaml while the other is the code behind, a more dynamic binding situation. 

Sometimes it helps to see a contrast if one is used to one or the other, a translation of sorts; so here it is:

Xaml Binding

The goal is to have the custom Slidebox control’s Spacing property to be bound to the TickTrack Control’s SpacingMargin property since these two controls have to work together (think of a slider control on a timeline).

If one were to do this in xaml it would look like this

    SecondsEnd="{Binding SecondsEnd, ElementName=userControl}"
    SecondsStart="{Binding SecondsStart, ElementName=userControl}"
    TickFrequency="{Binding TickFrequency, ElementName=userControl}" 
    HorizontalAlignment="Left" Width="{Binding Width, ElementName=userControl}" Height="59" Canvas.Top="70" />

<my:SlideBox Spacing="{Binding SpacingMargin, ElementName=tkTrack}"  />

The slidebox spacing is now uses the named tkTrack control’s dependent property  (not shown but publicly available property on TickTrack).

Code Behind Binding

If one were to do the same in code behind, say for a dynamically created custom slidebox control:

var bndSpacing = new Binding() 
                        Source = tkTrack, // Not the name but actual instance object
                        Path = new PropertyPath( "SpacingMargin" ) 

var sb = new SlideBox();

// "{Binding SpacingMargin, ElementName=tkTrack}"
sb.SetBinding( SlideBox.SpacingProperty,
               bndSpacing );

We create a binding instance with  the actual source and the path setup similar to xaml but different. The Source is not a named source but the actual object for the source to be bound to. Once we have the object, we then specify that the new slide box instance is to set the binding to the SpacingProperty (of the class description) dependency property of the slidebox instance.

Hope This Helps