【问题标题】:Bind a buttons visibility in XAML to a viewmodel?将 XAML 中的按钮可见性绑定到视图模型?
【发布时间】:2018-04-21 14:35:46
【问题描述】:

我希望按钮在 State.AwayState.Stop 中可见,但由于某种原因,即使 StateState.AwayState.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;
    }
}

【问题讨论】:

  • 您的虚拟机需要实现 INotifyPropertyChanged 并在 View 的值发生变化时引发 PropertyChanged 事件
  • 如果总是返回false,按钮是否不可见?那么绑定可能不知道当“状态”改变时“视图”改变了。
  • 另外,请确保控件的 DataContext 正确设置为您的 ViewModel
  • 我会考虑使用IValueConverterIsVisible 直接绑定到State,该IValueConverter 知道如何将状态映射到您想要的可见性。这样您就不必担心在多个属性上引发PropertyChanged,并且可以完全摆脱View,从而简化您的代码。

标签: c# xamarin mvvm xamarin.forms xamarin-studio


【解决方案1】:

您可以创建一个从StateVisibilityIValueConverter

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

【讨论】:

  • 您可能必须根据现有代码包含一些命名空间。如果你的真实代码与你的示例代码不完全匹配,他可能把一些类名弄错了。但从高层次来看,这都是正确和完整的。
猜你喜欢
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
相关资源
最近更新 更多