【问题标题】:Is there any way to bind Dictionary<enum, bool> to Switch in Xamarin.Forms?有没有办法将 Dictionary<enum, bool> 绑定到 Xamarin.Forms 中的 Switch?
【发布时间】:2019-12-13 04:52:55
【问题描述】:

我有一个字典,它来自一个 API,其中 enumeration 作为 keybool 作为 value例如:

Dictionary = new Dictionary<Permissions, bool>();
Dictionary.Add(Permissions.Create, true);
Dictionary.Add(Permissions.Delete, false);
...

我需要根据权限在 UI 上显示一堆开关,例如:

<Switch
  IsToggled="{Binding Dictionary[Create]}"/>
<Switch
  IsToggled="{Binding Dictionary[Delete]}"/>

但这不起作用。只有当 key 是一个字符串时它才能工作。

那么有什么方法可以使用带有枚举键的字典作为可绑定属性?

【问题讨论】:

  • 您是否尝试过使用您的字典作为带有自定义项目模板的列表框/列表视图的项目源,其中项目模板显示枚举/开关?除了为每个权限创建一个属性之外,我认为您无法以其他任何方式做到这一点。
  • 这行得通。但这看起来不是我想要实现的方式。我想在 Grid 的单元格内显示 Switches。

标签: c# dictionary xamarin enums binding


【解决方案1】:

您可以尝试使用中间变量。这是供您参考的代码。

Page1.xaml

<StackLayout Orientation="Horizontal">
        <Label Text="Create:Ture" VerticalOptions="Start"></Label>
        <Switch x:Name="SWitch" VerticalOptions="Start"  IsToggled="{Binding IsToggled}"></Switch>
    </StackLayout>

Page1.xaml.cs

public partial class Page1 : ContentPage
{

    public static Dictionary<string, bool> keyValuePairs = new Dictionary<string, bool>();
    public Page1()
    {
        InitializeComponent();
        keyValuePairs.Add("Create", true);
        SWitch.BindingContext = new SwitchModel(); 
    }
}

SwitchModel.cs

class SwitchModel : INotifyPropertyChanged
{

    bool isToggle;
    public SwitchModel()
    {
        IsToggled = Page1.keyValuePairs["Create"];
    }
    public bool IsToggled
    {
        set { SetProperty(ref isToggle, value); }
        get { return isToggle; }
    }
    bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (Object.Equals(storage, value))
            return false;
        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
 }

结果: enter image description here

【讨论】:

    【解决方案2】:

    IsToggled 绑定一个 bool 值,那么你必须绑定一个 bool 属性

    【讨论】:

      猜你喜欢
      • 2011-07-06
      • 2011-07-06
      • 2016-11-03
      • 2019-12-25
      • 1970-01-01
      • 2012-07-07
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多