3
votes

We have a UWP app using Template10. There is a textblock and textbox which show a discount. We wish to hide the textblock when ViewModel.Discount is null.

In App.xaml we have defined a converter

<T10Converters:ValueWhenConverter x:Key="HideWhenNullConverter" When="{x:Null}">
    <T10Converters:ValueWhenConverter.Value>
        <Visibility>Collapsed</Visibility>
    </T10Converters:ValueWhenConverter.Value>
    <T10Converters:ValueWhenConverter.Otherwise>
        <Visibility>Visible</Visibility>
    </T10Converters:ValueWhenConverter.Otherwise>
</T10Converters:ValueWhenConverter>

In the View we set the visibility of the TextBlock

Visibility="{x:Bind ViewModel.Discount, Converter={StaticResource HideWhenNullConverter}}"

In the ViewModel:

public class ViewModel : ViewModelBase
{
    decimal? _Discount = default(decimal?);
    public decimal? Discount
    {
        get
        {
            return _Discount;
        }
        set
        {
            if (value == 0) value = null;
            Set(ref _Discount, value);
        }
    }

However the textblock is always visible even if the value of ViewModel.Discount is null. How do we hide the textblock when ViewModel.Discount is null

1
You could also state that the Visibility logic is the responsibility of the ViewModel. The latest UWP can bind Visibility to a bool directly. Imagine you later have additional business rules, like a max price or so. - Henk Holterman
@HenkHolterman Nice, thanks for mentioning that - I've somehow missed this. - Romasz
In 14393, Visibility="{x:Bind ViewModel.Discount.HasValue, Mode=OneWay}". - Justin XL
Actually if you are using 14393 you should avoid converters as they are slow. Instead you can bind a function directly. - Justin XL
Yes @Justin XL that's what we have found ... converters are terribly slow. Thanks for the tip! - Vague

1 Answers

1
votes

As I've tried with Template10's source it should work. I suspect that you are just missing redefinition of Mode with x:Bind, which as default is OneTime. Try like this:

Visibility="{x:Bind ViewModel.Discount, Mode=OneWay, Converter={StaticResource HideWhenNullConverter}}"