【问题标题】:In UWP read-only calculated properties not updated in View在 UWP 中,只读计算属性未在视图中更新
【发布时间】:2017-07-23 03:07:37
【问题描述】:

我们正在使用 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 中有一个编辑 Net 的命令

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 在视图中正确更新。为什么视图中未更新税金和总计?

【问题讨论】:

  • 您在哪里增加税收和总计的财产变化?我认为在Set(ref _Net, value); 之后你应该有RaisePropertyChanged(nameof(Tax)); RaisePropertyChanged(nameof(Total));
  • 好问题@Romasz。我如何使用计算的属性来做到这一点? ...哎呀...刚刚得到您的编辑。
  • 我已经编辑了第一条评论。您是否有负责提高财产变更的公共/受保护/内部方法,还是只有Set()
  • 谢谢@Romasz。愿意回答吗?

标签: mvvm uwp template10


【解决方案1】:

它们不会在视图中更新,因为您没有通知它有关更改。您的 Set() 方法包含在 RaisePropertyChanged(string) 方法中(或类似的调用 PropertyChanged 事件),因此您的 Net 值更改正在显示,只需添加 Net 两者的设置器更改信息其他:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2020-09-13
    • 2018-12-11
    • 1970-01-01
    • 2021-03-08
    • 2019-04-18
    相关资源
    最近更新 更多