views:

1062

answers:

2

I have a TextBox that is bound to a Text-property on an Entity-object. I'd like to be able to re-format the text the user enters in some circumstances - e.g. if the user enters "2/4" (a fraction) - I'd like to change that to "1/2".

Via the “set-part” of the Text-property, I can change the value on the Entity-object, but that doesn't appear in the TextBox – it still reads “2/4”?

A: 

Did you implement INotifyPropertyChanged and call it?

    private string _fraction;

    public string Fraction
    {
        get { return _fraction; }
        set
        {
            _fraction = ReduceFraction(value);
            NotifyPropertyChanged("Fraction");
        }
    }

    private string ReduceFraction(string value)
    {
        string result = "1/2";
        // Insert reduce fraction logic here
        return result;
    }


    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
+6  A: 

The reason for this is that the binding system in WPF is "intelligent" and when you change the value in the TextBox it assumes that the PropertyChanged event will fire for that property and ignores it.

You can force the TextBox to refresh its bindings by calling:

textBox.GetBindingExpression(TextBox.TextProperty).UpdateTarget();

but the difficulty is finding a good place to hook this in. Obviously your data object can't do it since it has no reference to the TextBox instance. You could do it in the window that holds the TextBox by linking it to the PropertyChanged event handler of the data object, but that doesn't feel very clean.

I'll edit this response if I think of a better solution, but at least this explains the reason that the binding isn't working.


Aha! Changing the binding to IsAsync=true:

<TextBox x:Name="textBox" Text="{Binding Path=TestData, IsAsync=true}"/>

Appears to alter the behaviour so that it does pay attention to the PropertyChanged event when it's fired by the setter.

Martin Harris