Working with Binding data and UI elements in Silverlight 4

0
93
5 min read

Binding data to another UI element

Sometimes, the value of the property of an element is directly dependent on the value of the property of another element. In this case, you can create a binding in XAML called an element binding or element-to-element binding . This binding links both values. If needed, the data can flow bidirectionally.

In the banking application, we can add a loan calculator that allows the user to select an amount and the number of years in which they intend to pay the loan back to the bank, including (of course) a lot of interest.

Getting ready

To follow this recipe, you can either continue with your solution from the previous recipe or use the provided solution that can be found in the Chapter02/SilverlightBanking_ Element_Binding_Starter folder in the code bundle that is available on the Packt website. The finished application for this recipe can be found in the Chapter02/SilverlightBanking_Element_Binding_Completed folder.

How to do it…

To build the loan calculator, we’ll use Slider controls. Each Slider is bound to a TextBlock using an element-to-element binding to display the actual value. Let’s take a look at the steps we need to follow to create this binding:

  1. We will build the loan calculator as a separate screen in the application. Add a new child window called LoanCalculation.xaml. To do so, right-click on the Silverlight project in the Solution Explorer, select Add | New Item…, and choose Silverlight Child Window under Visual C#.
  2. Within MainPage.xaml, add a Click event on the LoanCalculationButton as shown in the following code:
    <Button x_Name="LoanCalculationButton"
    Click="LoanCalculationButton_Click" />
  3. In the code-behind’s event handler for this Click event, we can trigger the display of this new screen with the following code:
    private void LoanCalculationButton_Click(object sender,
    RoutedEventArgs e)
    {
    LoanCalculation loanCalculation = new LoanCalculation();
    loanCalculation.Show();
    }
  4. The UI of the LoanCalculation.xaml is quite simple—it contains two Slider controls. Each Slider control has set values for its Minimum and Maximum values (not all UI code is included here; the complete listing can be found in the finished sample code) as shown in the following code:
    <Slider x_Name="AmountSlider"
    Minimum="10000"
    Maximum="1000000"
    SmallChange="10000"
    LargeChange="10000"
    Width="300" >
    </Slider>
    <Slider x_Name="YearSlider"
    Minimum="5"
    Maximum="30"
    SmallChange="1"
    LargeChange="1"
    Width="300"
    UseLayoutRounding="True">
    </Slider>
  5. As dragging a Slider does not give us proper knowledge of where we are exactly between the two values, we add two TextBlock controls. We want the TextBlock controls to show the current value of the Slider control, even while dragging. This can be done by specifying an element-to-element binding as shown in the following code:
    <TextBlock x_Name="AmountTextBlock"
    Text="{Binding ElementName=AmountSlider, Path=Value}">
    </TextBlock>
    <TextBlock x_Name="MonthTextBlock"
    Text="{Binding ElementName=YearSlider, Path=Value}">
    </TextBlock>
  6. Add a Button that will perform the actual calculation called CalculateButton and a TextBlock called PaybackTextBlock to show the results. This can be done using the following code:
    <Button x_Name="CalculateButton"
    Content="Calculate"
    Click="CalculateButton_Click">
    </Button>
    <TextBlock x_Name="PaybackTextBlock"></TextBlock>
  7. The code for the actual calculation that is executed when the Calculate button is clicked uses the actual value for either the Slider or the TextBlock. This is shown in the following code:
    private double percentage = 0.0345;
    private void CalculateButton_Click(object sender,
    RoutedEventArgs e)
    {
    double requestedAmount = AmountSlider.Value;
    int requestedYears = (int)YearSlider.Value;
    for (int i = 0; i < requestedYears; i++)
    {
    requestedAmount += requestedAmount * percentage;
    }
    double monthlyPayback =
    requestedAmount / (requestedYears * 12);
    PaybackTextBlock.Text =
    "€" + Math.Round(monthlyPayback, 2);
    }

Having carried out the previous steps, we now have successfully linked the value of the Slider controls and the text of the TextBlock controls. The following screenshot shows the LoanCalculation.xaml screen as it is included in the finished sample code containing some extra markup:

How it works…

An element binding links two properties of two controls directly from XAML. It allows creating a Binding where the source object is another control. For this to work, we need to create a Binding and specify the source control using the ElementName property. This is shown in the following code:

<TextBlock Text="{Binding ElementName=YearSlider, Path=Value}" >
</TextBlock>

Element bindings were added in Silverlight 3. Silverlight 2 did not support this type of binding.

There’s more…

An element binding can also work in both directions, that is, from source to target and vice versa. This can be achieved by specifying the Mode property on the Binding and setting it to TwoWay.

The following is the code for this. In this code, we replaced the TextBlock by a TextBox. When entering a value in the latter, the Slider will adjust its position:

<TextBox x_Name="AmountTextBlock"
Text="{Binding ElementName=AmountSlider, Path=Value,
Mode=TwoWay}" >
</TextBox>

Element bindings without bindings

Achieving the same effect in Silverlight 2—which does not support this feature—is also possible, but only through the use of an event handler as shown in the following code. Element bindings eliminate this need:

private void AmountSlider_ValueChanged(object sender,
RoutedPropertyChangedEventArgs<double> e)
{
AmountSlider.Value = Math.Round(e.NewValue);
AmountTextBlock.Text = AmountSlider.Value.ToString();
}

See also

Element-to-element bindings can be easily extended to use converters. For more information on TwoWay bindings, take a look at the Using the different modes of data binding to allow persisting data recipe in this article.

Binding collections to UI elements

Often, you’ll want to display lists of data in your application such as a list of shopping items, a list of users, a list of bank accounts, and so on. Such a list typically contains a bunch of items of a certain type that have the same properties and need to be displayed in the same fashion.

We can use data binding to easily bind a collection to a Silverlight control (such as a ListBox or DataGrid) and use the same data binding possibilities to defi ne how every item in the collection should be bound. This recipe will show you how to achieve this.

Getting ready

For this recipe, you can fi nd the starter solution in the Chapter02/SilverlightBanking_ Binding_Collections_Starter folder and the completed solution in the Chapter02/SilverlightBanking_Binding_Collections_Completed folder in the code bundle that is available on the Packt website.

LEAVE A REPLY

Please enter your comment!
Please enter your name here