Arsen Zahray
Arsen Zahray

Reputation: 25287

How to implement 2-way binding between TextBox and double value?

Here's the code for my window:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="leartWPF.ControlTestWindow"
    x:Name="Window"
    Title="ControlTestWindow"
    Width="640" Height="480">

    <Grid x:Name="LayoutRoot">
        <TextBlock Height="26" Margin="45,26,241,0" TextWrapping="Wrap" Text="Please, enter an ariphmetical expression to calculate:" VerticalAlignment="Top"/>
        <TextBox Margin="48,72,63,201" TextWrapping="Wrap" Text="{Binding Input, ElementName=Window, FallbackValue=1+1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TextChanged="TextBox_TextChanged" >
        </TextBox>
        <!--<TextBlock Margin="282,208,266,167" TextWrapping="Wrap" Text="=" FontSize="64"/>-->
        <TextBlock Height="90" Margin="83,0,77,60" TextWrapping="Wrap" VerticalAlignment="Bottom" FontSize="48" Text="{Binding Result, ElementName=Window, Mode=TwoWay}"/>
        <Button Content="=" Height="27" Margin="233,0,263,166" VerticalAlignment="Bottom" FontSize="16"/>
    </Grid>
</Window>

and the class:

public partial class ControlTestWindow : Window
{
    private string _input;

    public double Result { get; set; }
    private static VsaEngine _engine = VsaEngine.CreateEngine();

    public string Input
    {
        get { return _input; }
        set
        {
            Result = double.Parse(Eval.JScriptEvaluate(value, _engine).ToString());
            _input = value;
        }
    }


    public ControlTestWindow()
    {
        this.InitializeComponent();

        // Insert code required on object creation below this point.
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
    }

}

The Input gets updated, and Result value changes, but it is never displayed on the appropriate TextBlock.

What should I change for this to work?

Upvotes: 1

Views: 1592

Answers (1)

Botz3000
Botz3000

Reputation: 39610

The TextBlock doesn't get notified of the change to the Result property. You have two options:

  1. Implement the property as a DependencyProperty. Visual studio has a code snippet for it. Type propdp and you'll see it pop up in intellisense.
  2. Implement INotifyPropertyChanged on your Window class and use it in your property.

Upvotes: 6

Related Questions