Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 212
Vague Avatar asked Jul 12 '26 09:07

Vague


1 Answers

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}}"
like image 154
Romasz Avatar answered Jul 14 '26 10:07

Romasz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!