更新模型時,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));
}
}
哪個安裝人員在檢查'SelectedEntity'或'Prop1'或'Prop2'? – Rafal
我不知道你是否注意到了,但是你的代碼中有一個錯誤{Binding SelectedEntity.Prop1,> Mode = TwoWay}「 - 注意'>'。同時在屬性 –
附近我正在檢查SelectedEntity, Prop1和Prop2,雖然在更新從UI綁定到SelectedEntity.Prop1的文本框時不會調用SelectedEntity的setter – user1041481