Search code examples
mvvmuwpuwp-xamltemplate10

UWP TextBlock does not update when bound to function


We are using UWP with Template10. Template10.ViewModelBase manages change notification. We have a CostTextBlock bound to ViewModel.Cost. Using a converter CostTextBlock updates when ViewModel.Cost updates. When we bind to a function, Cost renders in the correct format, but does not update. In the ViewModel we have:

public class ViewModel : ViewModelBase
{

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

Elsewhere in the ViewModel we update Cost:

this.Cost = null;

In App.xaml we define the converter:

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

In the view:

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

We can load the view with an order and Cost renders correctly. Using the converter, when Cost is set to null the change is reflected in the view.

We also have a method which does the same as the converter:

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

In which case the xaml in the view is

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

This correctly formats Cost in the view, but the same code used with the converter this.Cost = null; does not update the view even though Cost is updated.

Why is it that CostTextBlock does not reflect updates to ViewModel.Cost when it is bound to FormatPrice?


Solution

  • This issue occurred in a few properties which were updated from the viewmodel. I managed to work around this issue using RaisePropertyChanged(nameof(<property>));

    ViewModelBase is meant to handle change notification and it seems to do so in all cases where controls are bound to properties. If anyone can come up with a better solution or an explanation of why change notification isn't firing in these few cases where controls are bound to functions, I'll happily mark them as answer.