2017-03-01 116 views
0

更新模型時,UI會相應更新,但是當我更新具有雙向綁定的文本框時,不會調用視圖模型中的設置器。我究竟做錯了什麼?WPF雙向綁定未從UI更新

這裏是視圖模型如何綁定,以查看

public partial class MyView : MetroWindow 
{ 
    public MyView() 
    { 
     try 
     { 
      InitializeComponent(); 
      DataContext = new MyViewModel(new DialogService(this)); 
     } 
     catch (Exception exception) 
     { 
      throw exception; 
     } 
    } 
} 

XAML

<TextBox x:Name="TextBox1" Grid.Column="0" Text="{Binding SelectedEntity.Prop1, >Mode=TwoWay}" 
controls:TextBoxHelper.ClearTextButton="True" 
controls:TextBoxHelper.IsWaitingForData="True" 
controls:TextBoxHelper.UseFloatingWatermark="True" 
controls:TextBoxHelper.Watermark="{x:Static >properties:Resources.Prop1}" /> 
<TextBox x:Name="TextBox2" Grid.Column="0" Text="{Binding SelectedEntity.Prop2}" 
controls:TextBoxHelper.ClearTextButton="True" 
controls:TextBoxHelper.IsWaitingForData="True" 
controls:TextBoxHelper.UseFloatingWatermark="True" 
controls:TextBoxHelper.Watermark="{x:Static >properties:Resources.Prop2}"/> 

視圖模型

public class MyViewModel : IMyViewModel, INotifyPropertyChanged 
{ 

    private readonly IDialogService _dialogService; 
    public event PropertyChangedEventHandler PropertyChanged; 
    private readonly MyModel _model; 
    private MyEntity _selectedEntity; 

public MyViewModel(IDialogService dialogService) 
{ 
    _dialogService = dialogService; 

    _selectedEntity = new MyEntity(); 
    _model = new MyModel(); 
    _model.PropertyChanged += _model_PropertyChanged; 
} 

public MyEntity SelectedEntity 
{ 
    get 
    { 
      var information = _model.GetInformation(); 
      _selectedEntity.Flight = information.Prop1; 
      information.Destination = information.Prop2; 
      return _selectedEntity; 
    } 
    set 
    { 
     _selectedEntity = value; 
     OnPropertyChanged("SelectedEntity"); 
    } 
} 

private void OnPropertyChanged(string propertyName) 
{ 
    PropertyChanged?.Invoke(this, new   PropertyChangedEventArgs(propertyName)); 
} 

} 
+1

哪個安裝人員在檢查'SelectedEntity'或'Prop1'或'Prop2'? – Rafal

+2

我不知道你是否注意到了,但是你的代碼中有一個錯誤{Binding SelectedEntity.Prop1,> Mode = TwoWay}「 - 注意'>'。同時在屬性 –

+0

附近我正在檢查SelectedEntity, Prop1和Prop2,雖然在更新從UI綁定到SelectedEntity.Prop1的文本框時不會調用SelectedEntity的setter – user1041481

回答

2
<TextBox x:Name="TextBox1" Grid.Column="0" Text="{Binding SelectedEntity.Prop1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 

爲文本框默認UpdateSourceTrigger是引發LostFocus我相信,所以喲你需要明確地將其設置爲PropertyChanged。這種方式只要屬性發生變化就會觸發。

+1

另外,使用UpdateSourceTrigger = PropertyChanged可能仍然無法使用,具體取決於您使用的框架以及您的操作n綁定屬性的設置者,您可能會觸及此牆:https://sparethought.wordpress.com/2012/04/17/binding-to-wpf-textbox-seems-to-be-broken-in-net-4- 5-β/(解決方法:FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = FALSE;),因爲在他們4.5「固定」的錯誤和解決方法是在某些方面比wors的bug本身... – Arie

+0

使用UpdateSourceTrigger =的PropertyChanged不利於 – user1041481

+0

@ user1041481難道你在「Mode = TwoWay」之前刪除'>'? – Tesseract