Set IsVisible property by a string value of model

906 Views Asked by At

I am using XAML to define a ListView, with multiple buttons for each cell. I want to trigger visibility depending on whether a string value is empty or not. My button inside the ListView is:

<Button Text="{Binding Phone}" 
        Clicked="OnPhoneClicked"
        CommandParameter="{Binding Telefono}"
        x:Name="btnPhone" />

Binding Phone is read from my model. It is correctly shown.

How can set a IsVisible property button if Phone's value is an empty string?

1

There are 1 best solutions below

4
On

Try this code

<Button Text="{Binding Phone}" 
    Clicked="OnPhoneClicked"
    CommandParameter="{Binding Telefono}"
    x:Name="btnPhone"
    IsVisible="{Binding Phone,Converter={StaticResource StringNullOrEmptyBoolConverter"} />

StringNullOrEmptyBoolConverter.cs file

public class StringNullOrEmptyBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var s = value as string;
        return !string.IsNullOrWhiteSpace(s);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Finally add this in App.xaml file

 <Application.Resources>
        <ResourceDictionary>
            <Converter:StringNullOrEmptyBoolConverter x:Key="StringNullOrEmptyBoolConverter" />
        </ResourceDictionary>
    </Application.Resources>