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

时间:2009-03-31 21:37:26

标签: wpf textblock

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

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

5 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

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

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

答案 3 :(得分:0)

以下是使用代码隐藏的MSDN上的类似示例: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.targetupdated.aspx

答案 4 :(得分:0)

您可以使用我从Jerry Nixon和Daren May在Microsoft Virtual Academy“Developing Universal Windows Apps with C# and XAML”中获取的内容,包含DependencyObject逻辑的代码在此处为“(W8.1-WP8.1) UNIVERSAL APP FOR 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 { };
}
}

用法XAML:

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

用法xaml.cs:

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

用法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
}
}