简体   繁体   English

有什么办法绑定字典 <enum, bool> 切换到Xamarin.Forms?

[英]Is there any way to bind Dictionary<enum, bool> to Switch in Xamarin.Forms?

I have a Dictionary which comes from an API with enumeration as a key and bool as a value eg: 我有一个字典,该字典来自API, 枚举作为bool作为值,例如:

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

I need to show a bunch of Switches on UI accordingly to permissions eg: 我需要根据权限在UI上显示一堆开关,例如:

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

But this doesn't work. 但这是行不通的。 It could work only if key was a string. 仅当key是字符串时,它才能工作。

So is there any way to use Dictionary with enum key as a bindable property? 那么,有什么方法可以将带有枚举键的Dictionary用作可绑定属性?

You can try to use a intermediate variable. 您可以尝试使用中间变量。 Here is the code for your reference. 这是代码供您参考。

Page1.xaml 的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 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 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;
 }

The result: enter image description here 结果: 在此处输入图像描述

IsToggled与bool值绑定,然后必须将其与bool属性绑定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM