【发布时间】: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