2012-04-10 96 views
1

下面是我的窗口中的代碼:如何實現TextBox和double值之間的雙向綁定?

<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> 

和類:

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) 
    { 
    } 

} 

輸入得到更新,並結果值的變化,但它永遠不會顯示在相應的TextBlock 。

我應該改變這個工作?

回答

6

TextBlock不會收到有關Result屬性更改的通知。您有兩種選擇:

  1. 實施該屬性爲DependencyProperty。 Visual Studio有一個代碼片段。輸入propdp,你會看到它在intellisense中彈出。
  2. 在您的Window類上實現INotifyPropertyChanged並將其用於您的財產。
相關問題