在 UWP 中,只读计算属性未在视图中更新

In UWP read-only calculated properties not updated in View

我们正在使用 Template10 开发 UWP 应用程序。该应用程序正确显示成本、净额、税金和总计。 Tax 和 Total 是 ViewModel 中的计算属性。但是,当 Net 在 ViewModel 中更新时,Tax 和 Total 会在 ViewModel 中更新,但不会在 View 中更新。 Xaml:

<TextBlock 
    Text="{x:Bind ViewModel.Net,Mode=OneWay}"
/>
<TextBlock 
    Text="{x:Bind ViewModel.Tax,Mode=OneWay}"
/>
<TextBlock 
    Text="{x:Bind ViewModel.Total,Mode=OneWay}"
/>

视图模型:

public class ViewModel : ViewModelBase
{
        decimal? _Net = default(decimal?);
        public decimal? Net
        {
            get
            {
                return _Net;
            }
            set
            {
                if (value == 0) value = null;
                Set(ref _Net, value);
            }
        }

        decimal? _TaxRate = default(decimal?);
        public decimal? TaxRate { get { return _TaxRate; } set { Set(ref _TaxRate, value); } }

        public decimal? Tax
        {
            get
            {
                return TaxRate / 100 * Net;
            }
        }

        public decimal? Total { get { return Net + Tax; } }

我们在 ViewModel 中有一个编辑网络的命令

DelegateCommand _SetDiscount;
public DelegateCommand SetDiscount
       => _SetDiscount ?? (_SetDiscount = new DelegateCommand(() =>
       {
    // for simplicity deleted calculations for the newNet
           this.Net = newNet ?? 0;
}, () => true));

Net、Tax 和 Total 在 ViewModel 中正确更新。 Net 在视图中正确更新。为什么视图中的 Tax 和 Total 没有更新?

它们不会在 View 中更新,因为您没有通知它有关更改的信息。你的 Set() 方法有一个 RaisePropertyChanged(string) 方法(或类似调用 PropertyChanged 事件的方法)所以你的 Net 值变化正在显示,只需添加Net setter 更改另外两个的信息:

public decimal? Net
{
    get
    {
        return _Net;
    }
    set
    {
        if (value == 0) value = null;
        Set(ref _Net, value);
        RaisePropertyChanged(nameof(Total));
        RaisePropertyChanged(nameof(Tax));
    }
}