How to detect a change in the Text property of a TextBlock?

Bind the Text property to a DependencyProperty, which has an event trigger:

public static string GetTextBoxText(DependencyObject obj)
{
    return (string)obj.GetValue(TextBoxTextProperty);
}

public static void SetTextBoxText(DependencyObject obj, string value)
{
    obj.SetValue(TextBoxTextProperty, value);
}

public static readonly DependencyProperty TextBoxTextProperty =
    DependencyProperty.RegisterAttached(
    "TextBoxText",
    typeof(string),
    typeof(TextBlockToolTipBehavior),
    new FrameworkPropertyMetadata(string.Empty, TextBoxTextChangedCallback)
    );

private static void TextBoxTextChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    TextBlock textBlock = d as TextBlock;
    HandleTextChange(textBlock);
}

In the XAML Bind to the TextBlock text Property:

<TextBlock  
 Text="{Binding SomeProperty, UpdateSourceTrigger=PropertyChanged}"  
     th:TextBlockBehavior.TextBoxText="{Binding Text, 
     RelativeSource={RelativeSource Self}}" />

As far as I can understand there isn't any textchanged event in TextBlock. Looking at your requirement, I feel that re-templating a textbox will also not be a viable solution. From my preliminary searching around, this seems to be a possible solution.

<TextBlock x:Name="tbMessage" Text="{Binding Path=StatusBarText, NotifyOnTargetUpdated=True}">
    <TextBlock.Triggers>
        <EventTrigger RoutedEvent="Binding.TargetUpdated">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:0″
To="1.0″ />
                    <DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:2″
From="1.0″ To="0.0″ BeginTime="0:0:5″ />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </TextBlock.Triggers>
</TextBlock>

This is like the code from the link in bioskope's answer, but simplified. You need the TargetUpdated event and add NotifyOnTargetUpdated=True to the binding.

<TextBlock Text="{Binding YourTextProperty, NotifyOnTargetUpdated=True}" 
           TargetUpdated="YourTextEventHandler"/>

It's easier than that! Late answer, but much simpler.

// assume textBlock is your TextBlock
var dp = DependencyPropertyDescriptor.FromProperty(
             TextBlock.TextProperty,
             typeof(TextBlock));
dp.AddValueChanged(textBlock, (sender, args) =>
{
    MessageBox.Show("text changed");
});

Tags:

Wpf

Textblock