텍스트 블록의 텍스트 속성 변경을 감지하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/703167

  •  22-08-2019
  •  | 
  •  

문제

이벤트를 사용하여 텍스트 블록 요소의 텍스트 속성 변경을 감지하는 방법이 있습니까?

(저는 Datagrid 내에서 텍스트 속성이 변경되는 텍스트 블록을 강조하기위한 애니메이션을 제공하려고합니다)

도움이 되었습니까?

해결책

내가 이해할 수있는 한 TextBlock에는 TextChanged 이벤트가 없습니다. 귀하의 요구 사항을 살펴보면 텍스트 상자를 다시 설정하는 것도 실행 가능한 솔루션이 아니라고 생각합니다. 예비 검색에서 이것 가능한 해결책 인 것 같습니다.

다른 팁

그것보다 쉽습니다! 늦은 대답이지만 훨씬 간단합니다.

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

이것은 Bioskope의 답변 링크의 코드와 같지만 단순화되었습니다.

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

이벤트 트리거가있는 종속성 전문점에 텍스트 속성을 바인딩합니다.

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  
 Text="{Binding SomeProperty, UpdateSourceTrigger=PropertyChanged}"  
     th:TextBlockBehavior.TextBoxText="{Binding Text, 
     RelativeSource={RelativeSource Self}}" />

다음은 Code-Behind를 사용하는 MSDN의 유사한 예입니다.http://msdn.microsoft.com/en-us/library/system.windows.data.binding.targetupdated.aspx

다음은 Jerry Nixon과 Daren May에서 Microsoft Virtual Academy에서 픽업 한 내용입니다. "C# 및 XAML을 사용하여 범용 Windows 앱을 개발합니다"그리고 종속성 오브젝트 로직을 포함하는 코드는 여기에 있습니다."(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;

Usage 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
}
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top