Enum 綁定到 CheckBox

来源:https://www.cnblogs.com/ilison/archive/2018/04/10/8777876.html
-Advertisement-
Play Games

第一種方法: 後臺: 前臺: 此方法為泛型方法封裝,每次用時,都要寫一個轉換器,如:LogicalOperatorEnumConverter 。 第二種方法: 寫一個固定的類: 將Enum轉成ObservableCollection<ComboBoxDataModel> /// <summary> ...


第一種方法:

  後臺:

 internal static class EnumCache<T> 
        where T : struct, IConvertible
    {
        private static Dictionary<int, Tuple<T, string>> collectionCache;

        public static Dictionary<int, Tuple<T, string>> CollectionCache
        {
            get
            {
                if (collectionCache == null)
                {
                    collectionCache = CreateCache();
                }
                return collectionCache;
            }
        }

        private static Dictionary<int, Tuple<T, string>> CreateCache()
        {
            Dictionary<int, Tuple<T, string>> collectionCache = new Dictionary<int, Tuple<T, string>>();

            var fields = typeof(T).GetFields().Where(x => x.IsLiteral);

            foreach (var field in fields)
            {
                var intValue = (int)field.GetValue(null);
                var displayText = ((DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false))[0].Description;
                T operatorEnum = (T)(object)field.GetValue(null);
                var tuple = Tuple.Create(operatorEnum, displayText);
                collectionCache.Add(intValue, tuple);
            }
            return collectionCache;
        }
    }

    public class LogicalOperatorEnumConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //this is a hack, binding is unbinding to text i think???
            if (value is string)
            {
                value = LogicalOperator.Where;
            }

            return EnumCache<LogicalOperator>.CollectionCache[(int)value].Item2;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var displayText = (String)value;
            var key = EnumCache<LogicalOperator>.CollectionCache.Single(x => x.Value.Item2 == displayText).Key;
            return (object)EnumCache<LogicalOperator>.CollectionCache[key].Item1;
        }
    }

前臺:

<templates:LogicalOperatorEnumConverter x:Key="LogicalOperatorEnumConverter" />
<
ComboBox ToolTip="The logical operator" Grid.Column="1" Margin="2 0 0 0" ItemsSource="{Binding LogicalOperators}" SelectedItem="{Binding LogicalOperator, Mode=TwoWay}" > <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=. , Converter={StaticResource LogicalOperatorEnumConverter}}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>

此方法為泛型方法封裝,每次用時,都要寫一個轉換器,如:LogicalOperatorEnumConverter 。 

第二種方法:

  寫一個固定的類:

    

 public class ComboBoxDataModel : BaseEntity
    {
        private Guid _id;
        public Guid ID { get => _id; set => SetProperty(ref _id, value); }
        private string value;

        public string Value
        {
            get { return value; }
            set { this.value = value; OnPropertyChanged("Value"); }
        }
        private string text;

        public string Text
        {
            get { return text; }
            set { this.text = value; OnPropertyChanged("Text"); }
        }
        private bool isChecked;
        public bool IsChecked
        {
            get { return isChecked; }
            set { this.isChecked = value; OnPropertyChanged("IsChecked"); }
        }

    }

將Enum轉成ObservableCollection<ComboBoxDataModel>


/// <summary>
/// 枚舉轉換為List,顯示名稱為summary
/// </summary>
/// <param name="pEnum"></param>
/// <param name="pShowEnumValue">True:返回的是0,1,2等值;False:返回的是值對於的枚舉項目名稱</param>
/// <returns></returns>

public static ObservableCollection<ComboBoxDataModel> GetEnumList(Type pEnumType, bool pShowEnumValue = true)
        {
            ObservableCollection<ComboBoxDataModel> list = new ObservableCollection<ComboBoxDataModel>();
            Type typeDescription = typeof(DescriptionAttribute);
            System.Reflection.FieldInfo[] fields = pEnumType.GetFields();
            string strText = string.Empty;
            string strValue = string.Empty;
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    if (pShowEnumValue)
                    {
                        strValue = ((int)pEnumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                    }
                    else
                    {
                        strValue = pEnumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null).ToString();
                    }
                    object[] arr = field.GetCustomAttributes(typeDescription, true);
                    if (arr.Length > 0)
                    {
                        DescriptionAttribute aa = (DescriptionAttribute)arr[0];
                        strText = aa.Description;
                    }
                    else
                    {
                        strText = field.Name;
                    }
                    list.Add(new ComboBoxDataModel() { Text = strText, Value = strValue });
                }
            }
            return list;
        }

ViewModel:

 private ObservableCollection<ComboBoxDataModel> _enumBusinessPartDiscountTypeList;
        //數量範圍列表
        public ObservableCollection<ComboBoxDataModel> EnumBusinessPartDiscountTypeList
        {
            get => _enumBusinessPartDiscountTypeList;
            set
            {
                 SetProperty(ref _enumBusinessPartDiscountTypeList, value);
            }
        }

ctor中
 EnumBusinessPartDiscountTypeList =
                ComboBoxListHelper.GetEnumList(typeof(EnumBusinessPartDiscountType), true);

前臺:

 <ComboBox x:Name="cmbQuantitativeRange" Grid.Row="0" Grid.Column="3" DisplayMemberPath="Text" SelectedValuePath="Value"  Margin="5" Height="25"
                      ItemsSource="{Binding EnumBusinessPartDiscountTypeList}" 
                      SelectedItem="{Binding SelectedEnumBusinessPartDiscountType,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">                            
                        </ComboBox>

 

這種方式也可以,但需要寫更多的代碼,項目一開始用的是第二種。後來發現第一種,感覺第一種更比較好理解點。主要還是看項目需求,來選擇。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 當年面試一家公司,面試官問我:一個int類型的數組怎麼獲取裡面第二大的數字? 給了我一張紙和一支筆讓我寫一個方法,我想了想便寫了一個方法: 然後問我能不能優化一下你的代碼,我當然回答可以了,尷尬的就是我想了半天也想不出來,當時腦子一片空白........; 最後無奈的說:可以優化,但是我現在想不到! ...
  • 需求: 最近項目里遇到了個問題,對方沒有提供直接獲取數據源的api介面,而是通過郵件發數據的。這就需要接收郵件後解析郵件內容獲得數據。 分析: 想在代碼里實時獲取郵件,可以通過郵件的幾個協議來實現,常用的幾個協議有POP3協議,SMTP協議,IAMP協議。 1. pop3:(Post Office ...
  • Linq 雖然用得多,但是裡面有一些方法比較少用,因此整理一下。Enumerable 類的所有方法可以在 MSDN 上查閱到:https://msdn.microsoft.com/zh-cn/library/system.linq.enumerable.aspx Aggregate 這個方法有三個重 ...
  • 批註內容可以是對某段文字或內容的註釋,也可以是對文段中心思想的概括提要,或者是對文章內容的評判、疑問,以及在閱讀時給自己或他人起到提示作用。本篇文章中將介紹如何在C#中操作Word批註,主要包含以下要點: 插入Word批註 修改Word批註 刪除Word批註 使用工具:Free Spire.Doc ...
  • 新建用戶控制項取名:UserControl1,UserControl1繼承自上面新建的介面IObjectSafety,並實現介面(實現介面的方法請複製下麵的內容),在類UserControl1添加Guid特性值,利用VS的工具生成guid 進行簡單界面佈局: 點擊按鈕效果見上面代碼,還可自己寫一個公共 ...
  • MVC和三層架構 (有錯誤的話歡迎來噴,沒包袱) 一、概念 1、 MVC 最初的概念 輸入(控制器)、輸出(視圖)、邏輯處理(模型) 2、 三層架構 是對原始MVC概念中邏輯處理層(模型層)的進一步劃分,分UI-業務邏輯BLL-數據訪問DAL。三層里的模型是數據模型,與資料庫對應 但如今 MVC與三 ...
  • 上一篇文章中我們學習了列表頁面的結構,@page與@model兩個關鍵Razor指令,以及頁面佈局應該修改哪裡。這一篇文章我們來學習一下新建頁面。 ...
  • 本文的概念性內容來自深入淺出設計模式一書. 上一篇文章講了簡單工廠和工廠方法設計模式 http://www.cnblogs.com/cgzl/p/8760250.html, 使用的是披薩店的例子. 文將繼續使用這個例子, 這裡要用到抽象工廠. 披薩店的需求變更 現在披薩店在各地授權了很多連鎖分店, ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...