Как обнаружить изменение в свойстве Text TextBlock? - PullRequest
19 голосов
/ 01 апреля 2009

Есть ли способ обнаружить изменение свойства Text элемента TextBlock с помощью событий?

(я пытаюсь предоставить анимацию для выделения TextBlocks, свойство Text которых изменяется в DataGrid)

Ответы [ 6 ]

32 голосов
/ 26 августа 2015

Это проще, чем это! Поздний ответ, но намного проще.

// assume textBlock is your TextBlock
var dp = DependencyPropertyDescriptor.FromProperty(
             TextBlock.TextProperty,
             typeof(TextBlock));
dp.AddValueChanged(textBlock, (sender, args) =>
{
    MessageBox.Show("text changed");
});
12 голосов
/ 03 октября 2013

Это по ссылке в биоскопе ответ, но упрощенно.

<TextBlock Text="{Binding YourTextProperty, NotifyOnTargetUpdated=True}" 
           TargetUpdated="YourTextEventHandler"/>
2 голосов
/ 01 апреля 2009

Насколько я понимаю, в TextBlock нет события с измененным текстом. Глядя на ваше требование, я чувствую, что повторное шаблонирование текстового поля также не будет жизнеспособным решением. Из моих предварительных поисков, это представляется возможным решением.

1 голос
/ 18 февраля 2014

Свяжите свойство 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}}" />
0 голосов
/ 17 апреля 2015

Вот кое-что, что вы можете использовать, я взял у Джерри Никсона и Дарена Мея в Виртуальной академии Microsoft " Разработка универсальных приложений для Windows с C # и XAML ", а код, содержащий логику DependencyObject, здесь " 1003 * (W8.1-WP8.1) УНИВЕРСАЛЬНОЕ ПРИЛОЖЕНИЕ ДЛЯ 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
}
}
0 голосов
/ 18 октября 2012

Вот аналогичный пример на MSDN с использованием кода: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.targetupdated.aspx

...