zoukankan      html  css  js  c++  java
  • WPF中ComboBox控件绑定键值对操作

    WPF中下拉框将键值对作为其数据源的具体操作。本实例以枚举类型以及枚举特性描述字符串生成键值对来进行。

    namespace ViewC

    {
    /// <summary>
    /// View.xaml 的交互逻辑
    /// </summary>
    public partial class View : Window
    {

    private EnumType_enumType= EnumType.B;

    public View()
    {
      InitializeComponent();
      InitialComBox();
    }


    private void InitialComBox()
    {
      Dictionary<EnumType, string> keyValues = new Dictionary<EnumType, string>();
      var pro = typeof(EnumType).GetFields();//字段值
      for (int i = 0; i < pro.Count(); i++)
      {
        if (pro[i].FieldType.IsEnum)//枚举类型
        {
          var descrips = (DescriptionAttribute[])pro[i].GetCustomAttributes(typeof(DescriptionAttribute), false);//特性描述
          if (descrips.Length < 0) continue;
          var key = (EnumType)typeof(EnumType).InvokeMember(pro[i].Name, System.Reflection.BindingFlags.GetField, null, null, null);//根据枚举名称得到相应枚举值
          keyValues.Add(key, descrips[0].Description);
        }
      }
      cmbControlType.ItemsSource = keyValues;
      cmbControlType.DisplayMemberPath = "Value";
      cmbControlType.SelectedValuePath = "Key";
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
      //this.cmbControlType.SelectedValue = _controlStepType;//直接赋值selectvalue属性不会触发selectchanged事件
      this.cmbControlType.SelectedIndex = 0;
    }

    private void CmbControlType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      var controlType = (EnumType)this.cmbControlType.SelectedValue;
      //DoSomething

      MessageBox.Show(controlType .ToString());

    }

    }

    public enum EnumType
    {
      /// <summary>
      /// AA
      /// </summary>
      [Description("AA")]
      A,

      /// <summary>
      /// BB
      /// </summary>
      [Description("BB")]
      B,

      /// <summary>
      /// CC
      /// </summary>
      [Description("CC")]
      C,

    }
    }

  • 相关阅读:
    构造函数的继承
    创建一个不被销毁的空间 闭包小应用
    如何在Linux上恢复误删除的文件或目录
    一文详解 Ansible 自动化运维
    Shell 脚本编程最佳实践
    10 分钟看懂 Docker 和 K8S!
    BGP路由协议详解(完整版)
    浅析 Linux 中的零拷贝技术
    2020年DevOps工程师入门指南
    一条更新的SQL如何执行
  • 原文地址:https://www.cnblogs.com/VueDi/p/10904463.html
Copyright © 2011-2022 走看看