DependencyPropertyBehavior

  • 2 minutes to read

Sometimes, some properties of a UI control are not dependency properties, for instance, the TextBox.SelectedText property. This means the WPF binding system cannot target this property and the code below is not allowed

<TextBox Text="Select some text in this box" SelectedText="{Binding SelectedText, Mode=TwoWay}"/>

DependencyPropertyBehavior can be used to overcome such issues.

<TextBox Text="Select some text in this box">
    <dxmvvm:Interaction.Behaviors>
        <dxmvvm:DependencyPropertyBehavior PropertyName="SelectedText" EventName="SelectionChanged" Binding="{Binding SelectedText, Mode=TwoWay}"/>
    </dxmvvm:Interaction.Behaviors>
</TextBox>

To use the DependencyPropertyBehavior, it is necessary to set three its properties:

  • PropertyName - specifies the name of a property that should be bound.
  • Binding - specifies a binding that should be applied to the specified property.
  • EventName - specifies an event which the DependencyPropertyBehavior process to perform updating of the specified binding.

Example

<UserControl x:Class="Example.View.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ViewModel="clr-namespace:Example.ViewModel"
    xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignHeight="500" d:DesignWidth="600"
    DataContext="{dxmvvm:ViewModelSource Type=ViewModel:MainViewModel}">


    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
            <!--The TextBox.SelectedText property is not a dependency property-->
            <TextBox Width="200" Text="Select some text in this box">
                <dxmvvm:Interaction.Behaviors>
                    <dxmvvm:DependencyPropertyBehavior PropertyName="SelectedText" EventName="SelectionChanged" Binding="{Binding SelectedText, Mode=TwoWay}"/>
                </dxmvvm:Interaction.Behaviors>
            </TextBox>
            <TextBox Width="200" Text="{Binding SelectedText}" IsReadOnly="True"/>
        </StackPanel>
    </Grid>
</UserControl>