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"
        Title="MainWindow" Height="150" Width="360">
        <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"/>

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.


Leave a comment

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