[英]Implementation Of INotifyPropertyChanged In C# 6.0 - Why No Results?
因此,我已將ViewModel中的屬性綁定到TextBox中的屬性,並且我正在使用INotifyPropertyChanged的實現,以在適當的位置引發通知。 但是,我沒有在TextBox中看到正在更新的數據。 我的錯誤在哪里?
// ViewModel
namespace App1
{
public class Result
{
public string Message { get; set; }
}
public class ResultViewModel : INotifyPropertyChanged
{
private StringBuilder sb = new StringBuilder();
private CoreDispatcher dispatcher;
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
public string Results
{
get { return sb.ToString(); }
}
public int Count()
{
return sb.Length;
}
public ResultViewModel()
{
dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
}
public async Task Clear()
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => sb.Clear());
}
public async Task Add(Result result)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => sb.Append(result.Message));
OnPropertyChanged(nameof(Results));
}
}
}
Add通過MainPage.xaml.cs中的函數調用,如下所示...
private async void ShowResult(Result result)
{
await this.ViewModel.Add(result);
}
至於TextBox看起來像這樣...
// XAML
<TextBox x:Name="content"
Margin="0,10,0,10"
RelativePanel.AlignLeftWithPanel="True"
RelativePanel.Below="header"
RelativePanel.AlignRightWithPanel="True"
RelativePanel.Above="genButton"
TextWrapping="Wrap"
Text="{Binding Path=ViewModel.Results, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
TextChanged="content_TextChanged"/>
正如@JeroenvanLangen一樣,已經說過Add
的簽名沒有任何意義。
相反,您可以發出通知來指定受方法屬性名稱影響的通知:
OnPropertyChanged(nameof(Results));
CallerMemberName
的語法對屬性設置器很有用:
string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
OnPropertyChanged(); // will pass "Test" as propertyName
}
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
從其他地方調用此命令顯然是沒有意義的,例如:
void SomeMethod()
{
...
OnPropertyChanged(); // will pass "SomeMethod", huh?
}
View將收到此通知,但不會執行任何操作。
提示:如果要更新所有屬性,也可以傳遞空字符串""
,這同樣適用於您的情況(或者,如果您將Count
也設置為屬性並想綁定到它,則只有一個帶有""
通知會更新兩個Results
並在視圖中Count
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.