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,

}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM