2012-11-30 8 views
1

다음 샘플에서는 TextBox에 새 문자열을 입력하고 TabBlock을 눌렀을 때 TextBlock이 업데이트되지만 TextBox는 입력 한 값을 유지하면서 대신 수정 된 문자열로 업데이트됩니다 . 어떤 생각이 행동을 변경하는 방법?포커스 손실 후 TextBox의 TwoWay 바인딩이 업데이트되지 않습니다.

<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

덕분에 윈도우 폰 7이 "문제"가없는 나는 결국 이 코드를 사용하여 : CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync ( Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler (>) { MyProp = newValue; }})); – eih

+0

위대한 설명! 내 뷰 모델에는 Dispatcher가 없으므로 SynchronizationContext.Current.Post 메서드를 사용하여 바인딩 컨텍스트 외부에서 작업을 "대기열에 추가"했습니다. – Samuel

관련 문제