因此,我已经将视图模型中的属性绑定到文本框中的属性,并且正在使用 inotifyPropertychanged 的实现,以便在适当的位置提出通知。但是,我没有看到在文本框中更新数据。我的错误在哪里?
// 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?
}
视图将收到此通知,但不会做任何事情。
提示:如果要更新 ash all 属性,也可以传递空字符串""
,这将在您的情况下同等地工作(或者如果您还制作Count
也要属性并希望绑定到它,则在视图中,只有一个带有""
的通知Results
和Count
)。