Bind button visibility in XAML to viewmodel?

I want the button to be visible in State.Away and State.Stop, but for some reason the button is always displayed, even if the state is different from State.Away and State.Stop.

Xaml:

<Button Text="Hello" IsVisible="{Binding View}"/>

ViewModel:

private bool myBool;

public bool View
{
    get
    {
        if (State == State.Away || State == State.Gone)
        {
            myBool = true;
        }
        else
        {
            myBool = false;                   
        }
        return myBool;
    }
}
+4
source share
1 answer

You can create IValueConverterfrom StatetoVisibility

public class StateToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
    {
        if (value is State)
        {
            State state = (State)value;
            switch (state)
            {
                case State.Away:
                case State.Gone:
                    return Visibility.Visible;
                default:
                    return Visibility.Collapsed;
            }
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
    {
        return State.None; // your default state
    }
}

Then you bind your button to the converter

<Window.Resources>
    <local:StateToVisibilityConverter x:Key="StateToVisibilityConverter"/>
</Window.Resources>

<Button Text="Hello" Visibility="{Binding Path=State, Converter={StaticResource StateToVisibilityConverter}}"/>
+2
source

Source: https://habr.com/ru/post/1688958/


All Articles