2012-11-30 52 views
1

在以下示例中,當我在TextBox中鍵入新字符串並將Tab鍵輸出時,TextBlock被更新,但TextBox保留我輸入的值,而不是使用修改的字符串更新。任何想法如何改變這種行爲?TextBox中的雙向綁定在丟失焦點後未更新

<Page 
     x:Class="App1.MainPage" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="using:App1" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     mc:Ignorable="d"> 

     <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Margin="106,240,261,187"> 
      <StackPanel> 
       <TextBox Text="{Binding MyProp, Mode=TwoWay}"/> 
       <TextBlock Text="{Binding MyProp}"/> 
      </StackPanel> 
     </Grid> 
    </Page> 

public class ViewModel : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 

     public ViewModel() 
     { 
      MyProp = "asdf"; 
     } 

     protected virtual void OnPropertyChanged(string propertyName) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
     protected bool SetField<T>(ref T field, T value, string propertyName) 
     { 
      if (EqualityComparer<T>.Default.Equals(field, value)) return false; 
      field = value; 
      OnPropertyChanged(propertyName); 
      return true; 
     } 

     private string m_myProp; 

     public string MyProp 
     { 
      get { return m_myProp; } 
      set 
      { 
       m_myProp = value + "1"; 
       OnPropertyChanged("MyProp"); 
      } 
     } 
    } 

回答

2

您看到的行爲有些是預期的行爲。

當您從TextBox中跳出時,該綁定會調用MyProp設置器。當您調用OnPropertyChanged()時,您仍然處於原始綁定的上下文中,並且只有其他綁定會收到更改通知。 (爲了驗證它,在Getter上有一個斷點,並且看到它在OnPropertyChanged被調用後才被命中,解決方法是在初始化綁定完成更新後調用OnPropertyChanged,並通過調用方法來實現異步,而不是與等待其返回

更換調用OnPropertyChanged(「MyProp」):!

Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new 
Windows.UI.Core.DispatchedHandler(() => { OnPropertyChanged("MyProp"); })); 
+0

感謝小費的Windows Phone 7並沒有這個「問題」我結束了與此代碼:CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(()=> { MyProp = newValue; })); – eih

+0

很好的解釋!我使用SynchronizationContext.Current.Post方法來重新排列綁定上下文之外的工作,因爲我的視圖模型沒有Dispatcher。 – Samuel