编程语言
首页 > 编程语言> > c# – 将XAML中的按钮可见性绑定到视图模型?

c# – 将XAML中的按钮可见性绑定到视图模型?

作者:互联网

我希望按钮在State.Away和State.Stop中可见,但由于某种原因,即使State与State.Away和State.Stop不同,按钮也始终可见.

XAML:

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

视图模型:

private bool myBool;

public bool View
{
    get
    {
        if (State == State.Away || State == State.Gone)
        {
            myBool = true;
        }
        else
        {
            myBool = false;                   
        }
        return myBool;
    }
}

解决方法:

您可以从State到Visibility创建IValueConverter

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

然后将按钮绑定到转换器

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

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

标签:c,mvvm,xamarin,xamarin-forms,xamarin-studio
来源: https://codeday.me/bug/20190701/1348489.html