Quasimodo
Quasimodo

Reputation: 57

Binding gets an old value out of nowhere

I have a control which derives from a TextBox and has 2 additional string properties: Formula and FormulaResult (readonly):

public class SpreadsheetCellControl : TextBox, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };


    public string Formula
    {
        get;
        set;
    }
    public string FormulaResult
    {
        get
        {
            if (Formula != null && Formula != "")
            {
                string formula = Formula;
                formula = formula.StartsWith("=") ? formula.Substring(1) : formula;
                var calculation = Calculator.Calculate(formula);
                return calculation.Result.ToString();
            }
            else return "";
        }
    }

    protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
    {
        Formula = Text;
        base.OnPreviewLostKeyboardFocus(e);
    }
}

As defined in XAML, Text is bound to Formula when the control is focused and FormulaResult when it is not focused:

<Style TargetType="local:SpreadsheetCellControl" BasedOn="{StaticResource HoverableStyle}">
        <Setter Property="VerticalContentAlignment" Value="Center"/>

        <Setter Property="Text" Value="{Binding RelativeSource={RelativeSource self}, Path=FormulaResult, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"/>

        <Style.Triggers>
            <Trigger Property="IsFocused" Value="true">
                <Setter Property="BorderThickness" Value="2" />
                <Setter Property="BorderBrush" Value="Black" />
                <Setter Property="Text" Value="{Binding Formula, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
            </Trigger>

        </Style.Triggers>
    </Style>

Everything works as it should. For instance, I click the control, type for example "1/2", click anywhere else and it shows "0.5".

Then I set the Formula property from code-behind to "3" (any value actually). Before I click on the control, it shows all three properties correct: 3, 3 and 3. But when I click on the control, the Text property suddenly becomes the old "1/2", which is not stored anywhere. I checked that by placing a TextBlock and binding its Text to all three values of the cell control. Debugging also showed only new values.

P.S. Also "Formula" does not seem to take values by itself from "Text" here: Setter Property="Text" Value="{Binding Formula, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"

Upvotes: 2

Views: 60

Answers (1)

Clemens
Clemens

Reputation: 128061

The Binding in the Text property Setter inside the Trigger is missing RelativeSource Self:

<Setter Property="Text"
        Value="{Binding Path=Formula,
                        RelativeSource={RelativeSource Self},
                        Mode=TwoWay,
                        UpdateSourceTrigger=PropertyChanged}"/>

Upvotes: 2

Related Questions