Question

I'm have implemented a custom TextBox:

public class MyTextBox : TextBox
{
    // ...
}

that I'm using from XAML:

<MyTextBox Text="{Binding MyProperty}" />

and it's bound to a property in my ViewModel.

public class MyDataContext : INotifyPropertyChanged
{
    public string MyProperty
    {
        get { return _myPropertyBackingField; }
        set
        {
            _myPropertyBackingField = value;
            PropertyChanged(this, new PropertyChangedEventArgs("MyProperty"));
        }
    }

    // ...
}

Question: How can I, in MyTextBox, detect that MyProperty is changed?

MyProperty = "NewValue";

Preferably, I would like to distinguish a programmatical change from when the change was triggered by the user editing the value. That is, I don't think overriding OnPropertyChanged works for me.

Was it helpful?

Solution 2

OP here.

I realised after a while that it's the binding that keeps track of updating the TextBox from the source (DataContext). So a possible path to take would be to call GetBindingExpression(TextProperty) and work something out from that.

However, I solved it by overriding TextBoxBase.OnTextChanged:

protected override void OnTextChanged(TextChangedEventArgs e)
{
    base.OnTextChanged(e);
    if (!IsFocused)
    {
        // Do stuff here
    }
}

Since the control is not focused, the change must have been done programatically. This is not perfect since a programatical change might come when the TextBox has focus, but it is good enough for me.

OTHER TIPS

You can register to the PropertyChanged event of the TextBox's DataContext.

var dataContext = DataContext as MyDataContext;
dataContext.PropertyChanged += dataContext_PropertyChanged;

// check for the propertyname and react
void dataContext_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "MyProperty")
    {
        // Do things
    }
}

So if your viewmodel raises PropertyChanged you textbox also gets notified. But I think that's bad practice. What do you want to achieve?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top