在C#6.0中实现INotifyPropertyChanged - 为什么没有结果?

时间:2016-12-14 12:44:33

标签: c# viewmodel

因此,我已将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));
        }
    }
}

添加由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"/>

1 个答案:

答案 0 :(得分:1)

正如@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属性并希望绑定到它,然后只有一个通知""更新视图中的ResultsCount