我正在尝试从ViewModel更新WPF UI。
ViewModel:
ConcreteObserver : Observer<Mouse>, INotifyPropertyChanged
{
private string _key;
public DelegateCommand TestDelegateCommand { get; set; }
public string Key
{
get { return _key; }
set { _key = value;
OnPropertyChanged(nameof(Key));
}
}
public ConcreteObserver ()
{
TestDelegateCommand = new DelegateCommand(UpdateGui);
}
private void UpdateGui()
{
Key = "Test refresh";
}
public override void Update(TestObject subject)
{
Key = "Test Update";
if (subject is TestObject)
{
subject.MouseAction += OnMouse;
subject.Start();
}
}
private void OnMouse(object sender, RowMouseDataEventArgs e)
{
Key += "1";
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
风景:
<UserControl.DataContext>
<local:ConcreteObserver />
</UserControl.DataContext>
<Grid>
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding Key, UpdateSourceTrigger=PropertyChanged}" />
<Button
VerticalAlignment="Top"
HorizontalAlignment="Right"
Content="Click"
Command="{Binding TestDelegateCommand}" />
</Grid>
单击鼠标时触发了一个事件,该事件运行正常。
The problem that the UI is not updated if the Key
is changed within the Update
method and nothing is
displayed on the GUI if the Key
property changes.
I set a breakpoint and watched the change from the Key
property and everything works fine but the GUI doesn't recognize the change.
我用一个按钮对其进行了测试,单击该按钮时会显示更改。
有人可以向我解释原因。