繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM