【问题标题】:UWP TextBlock does not update when bound to functionUWP TextBlock 绑定到函数时不更新
【发布时间】:2017-07-31 03:25:56
【问题描述】:

我们正在使用带有 Template10 的 UWP。 Template10.ViewModelBase 管理变更通知。我们有一个CostTextBlock 绑定到ViewModel.Cost。当ViewModel.Cost 更新时,使用转换器CostTextBlock 更新。当我们绑定到一个函数时,Cost 会以正确的格式呈现,但不会更新。 在 ViewModel 中我们有:

public class ViewModel : ViewModelBase
{

    decimal? _Cost = default(decimal?);
    public decimal? Cost
    {
        get
        {
            return _Cost;
        }
        set
        {
            if (value == 0) value = null;
            Set(ref _Cost, value);
        }
    }

我们在 ViewModel 的其他地方更新 Cost:

this.Cost = null;

在 App.xaml 中我们定义了转换器:

<T10Converters:StringFormatConverter x:Key="PriceConverter" Format="{}{0:N2}"/>

在视图中:

Text="{x:Bind ViewModel.Cost,Mode=OneWay, Converter={StaticResource PriceConverter}}"/>

我们可以加载带有订单的视图并正确渲染成本。使用转换器,当 Cost 设置为 null 时,更改会反映在视图中。

我们还有一个和转换器一样的方法:

public static string FormatPrice(decimal? price)
{
    if (price == null)
        return null;
    return ((decimal)price).ToString("N2");
}

在这种情况下,视图中的 xaml 是

Text="{x:Bind Helpers:Globalisation.FormatPrice(ViewModel.Cost),Mode=OneWay}"

这可以正确格式化视图中的 Cost,但与转换器 this.Cost = null; 一起使用的相同代码不会更新视图,即使 Cost 已更新。

为什么CostTextBlock 绑定到FormatPrice 时没有反映对ViewModel.Cost 的更新?

【问题讨论】:

  • 是不是说只有cost为null才行不通?当 cost 为 null 时应该发生/显示什么? cost为null时字符串不应该为空吗?
  • @Romasz 当成本为空时,视图应显示空白成本。当我们使用转换器时就是这种情况。当我将控件绑定到 FormatPrice 时,视图中不会更新成本。如果我将 FormatPrice 更改为返回 String.Empty,则没有区别。成本仍未在视图中更新。
  • 在 null 情况下返回 0.0 不是更好吗?其次看看转换器是如何实现的,它可能会启发您作为使用转换器与静态方法的空案例的原因。
  • @mvermef 规范要求空白订单有空白成本。 FormatPrice 正确地将属性设置为 null。问题是为什么视图不更新。
  • 将 ViewModel.Cost 设置为 null 时是否调用转换器? x:Bind 不太喜欢空值。

标签: mvvm uwp uwp-xaml template10


【解决方案1】:

此问题发生在从视图模型更新的一些属性中。我设法使用RaisePropertyChanged(nameof(&lt;property&gt;));解决了这个问题

ViewModelBase 旨在处理更改通知,并且似乎在控件绑定到属性的所有情况下都这样做。如果有人能提出更好的解决方案或解释为什么在控件绑定到函数的少数情况下没有触发更改通知,我会很乐意将它们标记为答案。

【讨论】:

  • 您是否像示例if (value == 0) value = null; 那样在设置器中进行一些转换?只是因为 Set 方法仅在字段和值不相等时才会触发 PropertyChanged
  • 没错@Tóth Tibor.if (value != _Cost) { if (value == 0) value = null;
猜你喜欢
  • 1970-01-01
  • 2014-09-07
  • 1970-01-01
  • 2020-01-16
  • 2018-08-20
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多