如何检测TextBlock的Text属性的更改?

19 wpf textblock

有没有办法使用事件检测TextBlock元素的Text属性的更改?

(我正在尝试提供一个动画来突出显示TextBlocks,其Text属性在DataGrid中发生变化)

Ton*_*Nam 32

它比那更容易!迟到的答案,但更简单.

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

  • 你把 dp.AddValueChanged 放在哪里? (2认同)
  • 加载或构造函数听起来像个好地方. (2认同)

Mei*_*hes 13

这是来自bioskope答案的链接,但简单.

<TextBlock Text="{Binding YourTextProperty, NotifyOnTargetUpdated=True}" 
           TargetUpdated="YourTextEventHandler"/>
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,通过使用事件背后的代码,这应该是正确的答案。 (2认同)

小智 6

据我所知,TextBlock 中没有任何 textchanged 事件。看看您的要求,我觉得重新模板化文本框也不是一个可行的解决方案。从我的初步搜索来看,似乎是一个可能的解决方案。

<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>
Run Code Online (Sandbox Code Playgroud)