0

I have a string dependency property that I want to apply a "filter" to.

public string backup = string.Empty;

public static readonly DependencyProperty StringInTextBoxProperty =
                DependencyProperty.Register(
                    "StringInTextBox",
                    typeof(string),
                    typeof(MyClass),
                    new PropertyMetadata(OnStringInTextBoxChanged));

public string StringInTextBox
{
    get { return (string)GetValue(StringInTextBoxProperty); }
    set { SetValue(StringInTextBoxProperty, value); }
}

private static void OnStringInTextBoxChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
    // if(flag){
        if(filterPass){
            backup = StringInTextBox;
        }else{
            // flag = false
            StringInTextBox = backup;
            // flag = true
        }    
    // }
}

Everytime StringInTextBox changes, the filter is applied in OnStringInTextBoxChanged and if it passes the filter, it stays the same, otherwise, it goes back to a previous value. I save the "backup" value in a separate backup field.

The problem is that when I try to restore the previous value of StringInTextBox from backup, the method OnStringInTextBoxChanged is executed again since StringInTextBox is changing. It's kind of recursively calling the method.

The question is What is the right way to restore StringInTextBox to a previous value without triggering OnStringInTextBoxChanged more than once. I could use flags to bypass the method like in the commented lines above, but I feel that there is a better way to do it.

RF1991
  • 2,037
  • 4
  • 8
  • 17
Hans GD
  • 50
  • 9
  • You may add a [CoerceValueCallback](https://learn.microsoft.com/en-us/dotnet/api/system.windows.coercevaluecallback?view=windowsdesktop-7.0) with another [PropertyMetadata](https://learn.microsoft.com/en-us/dotnet/api/system.windows.propertymetadata.-ctor?view=windowsdesktop-7.0#system-windows-propertymetadata-ctor(system-object-system-windows-propertychangedcallback-system-windows-coercevaluecallback)) or FrameworkPropertyMetadata constructor. – Clemens Jul 18 '23 at 05:36
  • @Clemens Thanks! I didn't know those existed. – Hans GD Jul 18 '23 at 12:38

0 Answers0