wpf 如何检测 TextBlock 的 Text 属性的变化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/703167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:13:27  来源:igfitidea点击:

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

wpftextblock

提问by Tono Nam

Is there any way to detect a change in the Text property of a TextBlock element using events?

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

(I'm trying to provide an animation for highlighting the TextBlocks whose Text property change within a DataGrid)

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

采纳答案by bioskope

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, thisseems to be a possible solution.

据我所知,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>

回答by Tono Nam

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");
});

回答by Meirion Hughes

This is like the code from the link in bioskope's answer, but simplified. You need the TargetUpdatedevent and add NotifyOnTargetUpdated=Trueto the binding.

这类似于 bioskope 答案中链接中的代码,但已简化。您需要TargetUpdated事件并添加NotifyOnTargetUpdated=True到绑定中。

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

回答by Tal Segal

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

将 Text 属性绑定到一个 DependencyProperty,它有一个事件触发器:

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:

在 XAML 绑定到 TextBlock 文本属性中:

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

回答by Nasheayahu

Here's something you can use I picked up from Jerry Nixon and Daren May at the Microsoft Virtual Academy "Developing Universal Windows Apps with C# and XAML" and the code that contains the DependencyObject logic is here "(W8.1-WP8.1) UNIVERSAL APP FOR MVA".

这是我从 Jerry Nixon 和 Daren May 在微软虚拟学院“使用 C# 和 XAML 开发通用 Windows 应用程序”以及包含 DependencyObject 逻辑的代码这里获取的一些你可以使用的东西“ (W8.1-WP8.1) UNIVERSAL适用于 MVA 的应用程序”。

namespace App1.Behaviors
{
// <summary>
/// Helper class that allows you to monitor a property corresponding to a dependency property 
/// on some object for changes and have an event raised from
/// the instance of this helper that you can handle.
/// Usage: Construct an instance, passing in the object and the name of the normal .NET property that
/// wraps a DependencyProperty, then subscribe to the PropertyChanged event on this helper instance. 
/// Your subscriber will be called whenever the source DependencyProperty changes.
/// </summary>
public class DependencyPropertyChangedHelper : DependencyObject
{
    /// <summary>
    /// Constructor for the helper. 
    /// </summary>
    /// <param name="source">Source object that exposes the DependencyProperty you wish to monitor.</param>
    /// <param name="propertyPath">The name of the property on that object that you want to monitor.</param>
    public DependencyPropertyChangedHelper(DependencyObject source, string propertyPath)
    {
        // Set up a binding that flows changes from the source DependencyProperty through to a DP contained by this helper 
        Binding binding = new Binding
        {
            Source = source,
            Path = new PropertyPath(propertyPath)
        };
        BindingOperations.SetBinding(this, HelperProperty, binding);
    }

    /// <summary>
    /// Dependency property that is used to hook property change events when an internal binding causes its value to change.
    /// This is only public because the DependencyProperty syntax requires it to be, do not use this property directly in your code.
    /// </summary>
    public static DependencyProperty HelperProperty =
        DependencyProperty.Register("Helper", typeof(object), typeof(DependencyPropertyChangedHelper), new PropertyMetadata(null, OnPropertyChanged));

    /// <summary>
    /// Wrapper property for a helper DependencyProperty used by this class. Only public because the DependencyProperty syntax requires it.
    /// DO NOT use this property directly.
    /// </summary>
    public object Helper
    {
        get { return (object)GetValue(HelperProperty); }
        set { SetValue(HelperProperty, value); }
    }

    // When our dependency property gets set by the binding, trigger the property changed event that the user of this helper can subscribe to
    private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var helper = (DependencyPropertyChangedHelper)d;
        helper.PropertyChanged(d, e);
    }

    /// <summary>
    /// This event will be raised whenever the source object property changes, and carries along the before and after values
    /// </summary>
    public event EventHandler<DependencyPropertyChangedEventArgs> PropertyChanged = delegate { };
}
}

Usage XAML:

用法 XAML:

<TextBlock Grid.Row="0"
       x:Name="WritingMenuTitle"
       HorizontalAlignment="Left"
       FontSize="32"
       FontWeight="SemiBold"
       Text="{Binding WritingMenu.Title}"
       TextAlignment="Left"
       TextWrapping="Wrap"/>

Usage xaml.cs:

用法 xaml.cs:

Behaviors.DependencyPropertyChangedHelper helper = new Behaviors.DependencyPropertyChangedHelper(this.WritingMenuTitle, Models.CommonNames.TextBlockText);
helper.PropertyChanged += viewModel.OnSenarioTextBlockTextChangedEvent;

Usage viewmodel.cs:

用法 viewmodel.cs:

public async void OnSenarioTextBlockTextChangedEvent(object sender, DependencyPropertyChangedEventArgs args)
{
StringBuilder sMsg = new StringBuilder();

try
{
    Debug.WriteLine(String.Format(".....WritingMenuTitle : New ({0}), Old ({1})", args.NewValue, args.OldValue));
}
catch (Exception msg)
{
    #region Exception
    .....
    #endregion
}
}

回答by BryanJ