WPF组件内容在查看模型更改后未更新
我有以下视图模型:
public class ViewModel : ObservableObject
{
public string Watermark { get; set; } = "Loading...";
}
其中observableObject
来自Microsoft.toolkit.mvvm.com.ponentmodel
它实现inotifyPropertyChanged
和inotifyPropertyPropertyChanging
。
我有以下XAML:
<xctk:WatermarkTextBox>
<xctk:WatermarkTextBox.WatermarkTemplate>
<DataTemplate>
<ContentControl Content="{Binding DataContext.Watermark, RelativeSource={RelativeSource AncestorType=Window}}"></ContentControl>
</DataTemplate>
</xctk:WatermarkTextBox.WatermarkTemplate>
</xctk:WatermarkTextBox>
最后,以下C#代码:
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
Dispatcher.Invoke(() =>
{
// Assigning property of textbox directly with .Watermark = "" does not work
// Updating view model property doesn't work either
Model.Watermark = "Done";
});
}
当调用窗口加载方法时,Watermark Textbox的水印不会更新以反映其假定的新值,“ DONED”
。
可能缺乏一般的WPF理解,但是如果有人可以给出一个指针,以说明为什么会失败,我将非常感谢它。
谢谢!
I have the following view model:
public class ViewModel : ObservableObject
{
public string Watermark { get; set; } = "Loading...";
}
where ObservableObject
is from Microsoft.Toolkit.Mvvm.ComponentModel
which implements INotifyPropertyChanged
and INotifyPropertyChanging
.
I have the following XAML:
<xctk:WatermarkTextBox>
<xctk:WatermarkTextBox.WatermarkTemplate>
<DataTemplate>
<ContentControl Content="{Binding DataContext.Watermark, RelativeSource={RelativeSource AncestorType=Window}}"></ContentControl>
</DataTemplate>
</xctk:WatermarkTextBox.WatermarkTemplate>
</xctk:WatermarkTextBox>
And lastly the following C# code:
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
Dispatcher.Invoke(() =>
{
// Assigning property of textbox directly with .Watermark = "" does not work
// Updating view model property doesn't work either
Model.Watermark = "Done";
});
}
When the window loaded method gets called however, the watermark of the watermark textbox does not update to reflect its supposed new value, "Done"
.
It might be a lack of general WPF understanding but if anyone could give a pointer as to why this might fail I would greatly appreciate it.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法正确使用
observableObject
。这不是魔术(与某些使用Fody之类的框架的解决方案不同),因此您仍然必须自己完成工作以传播变化。请注意因此,您必须遵循这种模式:
You aren't using
ObservableObject
properly. It's not magic (unlike some solutions that use frameworks such as Fody), so you still have to do the work yourself to propagate changes. Note the example in the documentation.So you'll have to follow that pattern: