我有一个字典,它来自一个 API,枚举作为键,布尔值作为值,例如:
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]}"/>
但这行不通。仅当键是字符串时,它才能工作。
那么有没有办法将带有枚举键的字典用作可绑定属性呢?
您可以尝试使用中间变量。这是供您参考的代码。
第 1.xaml 页
<StackLayout Orientation="Horizontal">
<Label Text="Create:Ture" VerticalOptions="Start"></Label>
<Switch x:Name="SWitch" VerticalOptions="Start" IsToggled="{Binding IsToggled}"></Switch>
</StackLayout>
第 1.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();
}
}
交换机型号.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;
}
结果: 在此处输入图像描述
IsToggled 绑定一个布尔值,那么你必须用一个布尔属性绑定它