WPF使用枚举作多选设置的一种实现

基础类:

public class SelectItem
{
	public string Key { set; get; }
	public string Value { set; get; }
}


public class SettingsEnumList:ObservableCollection<SelectItem>
{
	public SettingsEnumList()
	{
		foreach (var item in typeof(SettingsEnum).GetEnumStructInfo())
		{
			Add(new SelectItem { Key = item.Id, Value = item.Description });
		}
	}
}
public static class EnumExtensions
    {
        /// <summary>
        /// 根据枚举获取属性值列表
        /// </summary>
        /// <param name="enumType">枚举</param>
        /// <returns></returns>
        public static List<StatusDictionary> GetSelectList(Type enumType)
        {
            var result = (from object e in Enum.GetValues(enumType)
                          let e1 = (int)e
                          select new StatusDictionary
                          {
                              Id = e1.ToString(),
                              Name = ((Enum)e).ToString(),
                              Description = GetDescription((Enum)e),
                          }).ToList();
            return result;
        }

        /// <summary>
        /// 根据枚举获取属性值列表
        /// </summary>
        /// <param name="enumType">枚举</param>
        /// <returns></returns>
        public static List<EnumStructInfo> GetEnumStructInfo(this Type enumType)
        {
            var result = (from object e in Enum.GetValues(enumType)
                          let e1 = (int)e
                          select new EnumStructInfo
                          {
                              Id = e1.ToString(),
                              Name = ((Enum)e).ToString(),
                              Description = GetDescription((Enum)e),
                              AdditionalInfo = GetAdditionalInfo((Enum)e),
                          }).ToList();
            return result;
        }

        /// <summary>
        /// 根据枚举成员获取属性描述
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum e)
        {
            //获取枚举的Type类型对象
            var type = e.GetType();

            //获取枚举的所有字段
            var field = type.GetField(e.ToString());
            if (field == null) return e.ToString();

            //第二个参数true表示查找EnumDisplayNameAttribute的继承链
            var cus = field.GetCustomAttributes(typeof(DescriptionAttribute), true);

            //如果没有找到自定义属性,直接返回属性项的名称
            var des = cus.Length > 0 && cus[0] != null && cus[0] is DescriptionAttribute obj ? obj.Description : e.ToString();

            return des;
        }

        /// <summary>
        /// 获取公司定义的标准返回码
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetHashEventCode(this EventSpecificType e)
        {
            return e.GetHashCode().ToString("0000");
        }

        public static string GetAdditionalInfo(this Enum e)
        {
            //获取枚举的Type类型对象
            var type = e.GetType();

            //获取枚举的所有字段
            var field = type.GetField(e.ToString());

            //第二个参数true表示查找EnumDisplayNameAttribute的继承链
            var cus = field.GetCustomAttributes(typeof(AdditionalInfoAttribute), true);

            //如果没有找到自定义附加属性,直接返回属性项的名称
            var info = cus.Length > 0 && cus[0] is AdditionalInfoAttribute obj ? obj.AdditionalInfo : e.ToString();

            return info;
        }

        /// <summary>
        /// 获取业务定义的标准返回码
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static int GetBusinessCode(this ApiResultEnum e)
        {
            var busCode = int.TryParse(AppConfig.ProjectCode, out var prjCode) ? prjCode : 50;

            var code = (int)e;
            if (code == 0 || code == 1) return code;

            var result = busCode + code.ToString().PadLeft(ValuesConstant.BusinessCodeLength - busCode.ToString().Length, '0');
            return Convert.ToInt32(result);
        }
    }

XAML:

<common:SettingsEnumList x:Key="SettingsEnumList" />

<ItemsControl Grid.Column="1"
			  Width="550"
			  HorizontalAlignment="Left"
			  VerticalAlignment="Center"
			  ItemsSource="{StaticResource SettingsEnumList}">
	<ItemsControl.ItemTemplate>
		<DataTemplate>
			<CheckBox Width="90"
								Margin="0,0,0,34"
								VerticalContentAlignment="Center"
								Command="{Binding Path=DataContext.SelectSettingCommand, ElementName=Main}"
								CommandParameter="{Binding Path=Key}"
								Content="{Binding Value}"
								FontSize="16"
								FontWeight="Light">
				<CheckBox.IsChecked>
					<MultiBinding Converter="{StaticResource String2CheckBoxConverter}" Mode="OneWay">
						<MultiBinding.Bindings>
							<Binding ElementName="Main" Path="DataContext.SelectedSettings" />
							<Binding Path="Key" />
						</MultiBinding.Bindings>
					</MultiBinding>
				</CheckBox.IsChecked>
			</CheckBox>
		</DataTemplate>
	</ItemsControl.ItemTemplate>
	<ItemsControl.ItemsPanel>
		<ItemsPanelTemplate>
			<WrapPanel />
		</ItemsPanelTemplate>
	</ItemsControl.ItemsPanel>
</ItemsControl>

Converter:

public class String2CheckBoxConverter : IMultiValueConverter
{
	public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
	{
		bool result = false;
		if (values.Length >= 2)
		{
			if (values[0] == null)
			{
				values[0] = "";

			}
			result = values[0].ToString().Split(',').Contains(values[1].ToString());
		}
		return result;
	}

	public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
	{
		throw new NotImplementedException();
	}
}

 

VM:


private string _selectedSettings = string.Empty;

public string SelectedSettings
{
	get => _selectedSettings;
	set => SetPropertyNotify(ref _selectedSettings, value);
}


private async Task OnSelectSetting(string arg)
{
	await TaskEx.FromResult(0);

	var list = SelectedSettings?.Split(',').ToList();
	var isContain = list != null && list.Contains(arg);
	//每次点击处理选中项目
	var newSelected = "";
	if (isContain)
	{
		list.Remove(arg);

		newSelected = string.Join(",", list.Where(o => !string.IsNullOrEmpty(o)).ToArray());
		SelectedSettings = newSelected;

	}
	else
	{
		SelectedSettings += "," + arg;
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值