C# WPF Data Binding and Binding Direction


Continuing with the text box and slider example in the book Illustrated WPF by Daniel M. Solis, here we do something a bit different. We reverse the direction of the binding (Mode=OneWayToSource). The following is the same markup but with the Mode set to OneWayToSource. In this case, if you enter a value in the TextBox and change focus, the slider is updated. But if you drag the slider, the TextBox is not updated.

This seems a bit strange. Why not just put the binding on the other element? One reason is that the source property might not be a dependency property. In that case, you can’t switch them, because the target property must always be a dependency property.

<Window x:Class="DataBinding4.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:DataBinding4"
        mc:Ignorable="d"
        Title="MainWindow" Height="150" Width="360">
    <StackPanel>
        <TextBox Margin="10" Name="tbValue" Text="{Binding ElementName=sldrSlider, Path=Value, Mode=OneWayToSource}"/>
        <Slider Name="sldrSlider" TickPlacement="TopLeft" Margin="10" Maximum="10"/>
        <Label x:Name="label" Content="Book: Illustrated WPF by Daniel M. Solis, Ch 8 page 196" HorizontalAlignment="Left" Height="26" Margin="10,0,0,0" Width="323"/>
    </StackPanel>
</Window>

Suppose, for example, that you had a TextBox that you wanted to bind to a property that was not a dependency property, and you wanted to update that property when the text in the TextBox changed. Logically, the TextBox is the source, and the other property is the target. But the plumbing of bindings relies on some of the features of the dependency property system and therefore requires that the target be a dependency property. To get around this, you can reverse both the roles (target and source) and the direction of the updating, using Mode=OneWayToSource.

DataBinding4

Leave a comment

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