C# WPF Multiple Bindings on an Object


In this C# WPF example, we offer the user several ways to change a single control on the window. That control is simply some text. Text has several properties such as font, bold, italic and colour. and the user makes their choices using more than one control – one control for each property. You have multiple sources and one target. The code for that example comes from the book Illustrated WPF.

From the opposite perspective, you may offer the user one control that, if selected, changes a wholw set of properties of an object. It would be like choosing a skin or colour theme for an application. The user chooses “Light Blue” from a list of choices and that affects several controls and windows in the application. This scenario is not discussed here.

For example, the window shown below contains a Label at the top and two ComboBoxes beneath it. The top ComboBox contains a list of font families and is bound to the FontFamily property of the Label. The second ComboBox contains a set of FontWeights and is bound to the FontWeight property of the Label. When a new selection is made in either of the ComboBoxes the text in the Label reflects the change.

MultipleBindingsonaTextbox

<Window x:Class="MultipleBindingsOnAnElement.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MultipleBindingsOnAnElement"
        mc:Ignorable="d"
        Title="MainWindow" Height="150" Width="225">
    <StackPanel>
        <Label Name="displayText" Margin="5" FontSize="16" Content="My Text"
             FontFamily="{Binding ElementName=fontBox, Path=Text}"
             FontWeight="{Binding ElementName=weightBox, Path=Text}"/>
        <ComboBox Name="fontBox" SelectedIndex="0" Margin="5,0,5,2">
            <ComboBoxItem>Arial</ComboBoxItem>
            <ComboBoxItem>Courier New</ComboBoxItem>
        </ComboBox>
        <ComboBox Name="weightBox" SelectedIndex="0" Margin="5,0,5,2">
            <ComboBoxItem>Normal</ComboBoxItem>
            <ComboBoxItem>Bold</ComboBoxItem>
        </ComboBox>
    </StackPanel>
</Window>

Here is a diagram from the book Illustrated WPF.

DiagramMultipleBindings

Leave a comment

Your email address will not be published. Required fields are marked *