我有以下視圖模型:
public class ViewModel : ObservableObject
{
public string Watermark { get; set; } = "Loading...";
}
哪里ObservableObject是從Microsoft.Toolkit.Mvvm.ComponentModel哪個實作INotifyPropertyChanged和INotifyPropertyChanging。
我有以下 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";
});
}
但是,當呼叫視窗加載方法時,水印文本框的水印不會更新以反映其假定的新值,"Done".
這可能是缺乏對 WPF 的一般理解,但如果有人能指出為什么這可能會失敗,我將不勝感激。
謝謝!
uj5u.com熱心網友回復:
你沒有ObservableObject正確使用。這不是魔術(不像某些使用框架的解決方案,如 Fody),所以您仍然必須自己完成作業來傳播更改。請注意檔案中的示例。
public class User : ObservableObject
{
private string name;
public string Name
{
get => name;
set => SetProperty(ref name, value);
}
}
所以你必須遵循這個模式:
public class ViewModel : ObservableObject
{
private string watermark;
public ViewModel()
{
Watermark = "Loading...";
}
public string Watermark
{
get => watermark;
set => SetProperty(ref watermark, value);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482038.html
上一篇:將GoogleAppEngine服務映射到Cloudflare
下一篇:游戲物件找不到它的父物件
