我们使用UWP和Template10。 Template10.ViewModelBase
管理变更通知。我们有一个CostTextBlock
绑定到ViewModel.Cost
。 ViewModel.Cost
更新时使用转换器CostTextBlock
更新。当我们绑定到一个函数时,Cost会以正确的格式呈现,但不会更新。 在视图模型,我们有:当绑定到函数时,UWP TextBlock不会更新
public class ViewModel : ViewModelBase
{
decimal? _Cost = default(decimal?);
public decimal? Cost
{
get
{
return _Cost;
}
set
{
if (value == 0) value = null;
Set(ref _Cost, value);
}
}
别处在视图模型,我们更新成本:
this.Cost = null;
在App.xaml中,我们定义转换器:
<T10Converters:StringFormatConverter x:Key="PriceConverter" Format="{}{0:N2}"/>
在视图:
Text="{x:Bind ViewModel.Cost,Mode=OneWay, Converter={StaticResource PriceConverter}}"/>
我们可以使用订单加载视图并正确呈现成本。使用转换器时,当“成本”设置为空时,更改将反映在视图中。
我们也有不一样的转换器的方法:
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}"
这正确地格式化在视图中的成本,但是即使更新成本,转换器this.Cost = null;
使用的相同代码也不更新视图。
为什么CostTextBlock
不反映更新到ViewModel.Cost
当它绑定到FormatPrice
?
这是否意味着它仅在成本为* null *时才起作用?当成本为* null *时应该发生什么?成本为空时不应该为空字符串? – Romasz
@Romasz当成本为空时,视图应显示空白成本。当我们使用转换器时就是这种情况。当我将控件绑定到FormatPrice时,视图中的成本不会更新。如果我将FormatPrice更改为返回String.Empty,则没有区别。成本仍然不会在视图中更新。 – Vague
在null情况下返回0.0会不会更好?其次,看看转换器是如何实现的,它可能会启发你作为空转换器与静态方法相结合的原因。 – mvermef