Search code examples
xamluwptemplate10

Hide xaml element when null


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


Solution

  • 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}}"