我正在尝试从ViewModel更新WPF UI。
风景:
<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>
ViewModel:
ConcreteObserver : Observer<Mouse>, INotifyPropertyChanged
{
private string _key;
public DelegateCommand TestDelegateCommand { get; set; }
public string Key
{
get { return _key; }
set { 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));
}
}
单击鼠标时触发了一个事件,该事件运行正常。
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.
我用一个按钮对其进行了测试,单击该按钮时会显示更改
有人可以向我解释原因。
谢谢
The setter of your
Key
property does not set any value to the backing field. You're only firing thePropertyChanged
event.首先设置值,然后触发事件:
Additionally, as a side note, I'd like to mention that you are using the
CallerMemberName
attribute in yourOnPropertyChanged
method ......所以你可以/应该写...
... 代替 ...