簡體   English   中英

在C#中從枚舉創建RadioButton

[英]Creating RadioButtons from an enum in C#

我想用一個與枚舉值對應的RadioButton對象填充StackPanel 每個按鈕的處理程序應運行任意計算,該計算采用相應的枚舉值。

這是我提出的方法:

void EnumToRadioButtonPanel(Panel panel, Type type, Action<int> proc)
{
    Array.ForEach((int[])Enum.GetValues(type),
        val =>
        {
            var button = new RadioButton() { Content = Enum.GetName(type, val) };
            button.Click += (s, e) => proc(val);
            panel.Children.Add(button);
        });
}

例如,假設我希望RadioButton用於枚舉FigureHorizontalAnchor 我想要每個按鈕的動作來設置一個名為figure的特定FigureHorizontalAnchor屬性。 這是我如何調用EnumToRadioButtonPanel

var figure = new Figure();

var stackPanel = new StackPanel();

EnumToRadioButtonPanel(stackPanel, typeof(FigureHorizontalAnchor),
    val =>
    {
        figure.HorizontalAnchor = (FigureHorizontalAnchor)
            Enum.ToObject(typeof(FigureHorizontalAnchor), val);
    });

我的問題是,有沒有更好的方法來實現這一目標? 我應該使用“綁定”技術嗎? 我在SO上看到了幾個相關的問題,但是它們涉及在XAML中布置RadioButton ; 我想通過C#背后的代碼來做到這一點。

這是上面完整的可運行演示。 XAML:

<Window x:Class="EnumToRadioButtonPanel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

</Window>

代碼背后:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace EnumToRadioButtonPanel
{
    public partial class MainWindow : Window
    {
        void EnumToRadioButtonPanel(Panel panel, Type type, Action<int> proc)
        {
            Array.ForEach((int[])Enum.GetValues(type),
                val =>
                {
                    var button = new RadioButton() { Content = Enum.GetName(type, val) };
                    button.Click += (s, e) => proc(val);
                    panel.Children.Add(button);
                });
        }

        public MainWindow()
        {
            InitializeComponent();

            var figure = new Figure();

            var stackPanel = new StackPanel();

            Content = stackPanel;

            EnumToRadioButtonPanel(stackPanel, typeof(FigureHorizontalAnchor),
                val =>
                {
                    figure.HorizontalAnchor = (FigureHorizontalAnchor)
                        Enum.ToObject(typeof(FigureHorizontalAnchor), val);
                });

            var label = new Label();

            stackPanel.Children.Add(label);

            var button = new Button() { Content = "Display" };

            button.Click += (s, e) => label.Content = figure.HorizontalAnchor;

            stackPanel.Children.Add(button);
        }
    }
}

如你所知,有更多的“WPF”方法可以做到這一點。

不要通過代碼創建控件。 WinForms來說有點好,但是你不想在WPF中做到這一點。

如果ItemsControl項列表中創建控件集合,請使用ItemsControl

<ItemsControl Source="{Binding ItemsIWantToCreateControlsFor}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <RadioButton
        Content="{Binding APropertyDefinedInMyItem}"
        Command="{Binding ACommandDefinedInMyItemThatIsExecutedWhenPressed}"/>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

這是EnumToRadioButtonPanel的另一個版本,它似乎通過在類型上具有通用性而導致更清晰的代碼。

void EnumToRadioButtonPanel<T>(Panel panel, Action<T> proc)
{
    Array.ForEach((int[])Enum.GetValues(typeof(T)),
        val =>
        {
            var button = new RadioButton() { Content = Enum.GetName(typeof(T), val) };
            button.Click += (s, e) => proc((T)Enum.ToObject(typeof(T),val));
            panel.Children.Add(button);
        });
}

在此版本中,對EnumToRadioButtonPanel的調用如下所示:

EnumToRadioButtonPanel<FigureHorizontalAnchor>(
    stackPanel,
    val => figure.HorizontalAnchor = val);

代替:

EnumToRadioButtonPanel(stackPanel, typeof(FigureHorizontalAnchor),
    val =>
    {
        figure.HorizontalAnchor = (FigureHorizontalAnchor)
            Enum.ToObject(typeof(FigureHorizontalAnchor), val);
    });

以下是整個示例。 XAML:

<Window x:Class="EnumToRadioButtonPanel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

</Window>

C#:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace EnumToRadioButtonPanel
{
    public partial class MainWindow : Window
    {
        void EnumToRadioButtonPanel<T>(Panel panel, Action<T> proc)
        {
            Array.ForEach((int[])Enum.GetValues(typeof(T)),
                val =>
                {
                    var button = new RadioButton() { Content = Enum.GetName(typeof(T), val) };
                    button.Click += (s, e) => proc((T)Enum.ToObject(typeof(T),val));
                    panel.Children.Add(button);
                });
        }

        public MainWindow()
        {
            InitializeComponent();

            var figure = new Figure();

            var stackPanel = new StackPanel();

            Content = stackPanel;

            EnumToRadioButtonPanel<FigureHorizontalAnchor>(
                stackPanel,
                val => figure.HorizontalAnchor = val);

            var label = new Label();

            stackPanel.Children.Add(label);

            var button = new Button() { Content = "Display" };

            button.Click += (s, e) => label.Content = figure.HorizontalAnchor;

            stackPanel.Children.Add(button);
        }
    }
}

創建字典<enum, list<objec> &gt; 從列表<object>使用 LINQ C#<div id="text_translate"><p> 我有以下枚舉和 class:</p><pre> public enum SymbolTypeEnum { [Description("Forex")] forex = 0, [Description("Metals")] metals = 1, [Description("Commodities")] commodities = 2, [Description("Indices")] indices = 3, [Description("Cryptocurrency")] cryptocurrency = 4, [Description("Other")] other = 5 } public enum SymbolClassificationEnum { [Description("None")] none = 0, [Description("Major")] major = 1, [Description("Minor")] minor = 2, [Description("Exotic")] exotic = 3 } public class SymbolSettingsModel { [PrimaryKeyAttribute, Unique] public string symbolName { get; set; } public SymbolTypeEnum symbolType { get; set; } public SymbolClassificationEnum symbolClassification { get; set; } }</pre><p> 我有一個List&lt;SymbolSettingsModel&gt; symbolSettings;</p><p> 我的目標是生成Dictionary&lt;SymbolTypeEnum, List&lt;SymbolDescr&gt;&gt; typeSymbolsSettingsData;</p><p> SymbolDescr 在哪里:</p><pre> class SymbolDescr { public string symbol { get; set; } public int classification { get; set; } }</pre><p> 想法是按 symbolType 對它們進行分組,並將其用作字典的 Key,並生成 SymbolDescr 列表。 到目前為止,這是我的代碼:</p><pre> typeSymbolsSettingsData = symbolSettings.GroupBy(p =&gt; p.symbolType).ToDictionary(p =&gt; p.Key, p =&gt; p.ToList());</pre><p> 我被困在這一點上,你有什么想法我該怎么做嗎?</p></div></object></enum,>

[英]Creating Dict<enum, List<objec>> from List<object> using LINQ C#

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 用radiobuttons創建一個輸入框c# 枚舉和單選按鈕 在C#中添加單選按鈕和RatingView 所有單選按鈕均已檢查c# 使用枚舉C#創建具體類的接口? 創建沒有0值的C#Enum實例 C#創建具有相關枚舉子列表的主枚舉列表 創建字典<enum, list<objec> &gt; 從列表<object>使用 LINQ C#<div id="text_translate"><p> 我有以下枚舉和 class:</p><pre> public enum SymbolTypeEnum { [Description("Forex")] forex = 0, [Description("Metals")] metals = 1, [Description("Commodities")] commodities = 2, [Description("Indices")] indices = 3, [Description("Cryptocurrency")] cryptocurrency = 4, [Description("Other")] other = 5 } public enum SymbolClassificationEnum { [Description("None")] none = 0, [Description("Major")] major = 1, [Description("Minor")] minor = 2, [Description("Exotic")] exotic = 3 } public class SymbolSettingsModel { [PrimaryKeyAttribute, Unique] public string symbolName { get; set; } public SymbolTypeEnum symbolType { get; set; } public SymbolClassificationEnum symbolClassification { get; set; } }</pre><p> 我有一個List&lt;SymbolSettingsModel&gt; symbolSettings;</p><p> 我的目標是生成Dictionary&lt;SymbolTypeEnum, List&lt;SymbolDescr&gt;&gt; typeSymbolsSettingsData;</p><p> SymbolDescr 在哪里:</p><pre> class SymbolDescr { public string symbol { get; set; } public int classification { get; set; } }</pre><p> 想法是按 symbolType 對它們進行分組,並將其用作字典的 Key,並生成 SymbolDescr 列表。 到目前為止,這是我的代碼:</p><pre> typeSymbolsSettingsData = symbolSettings.GroupBy(p =&gt; p.symbolType).ToDictionary(p =&gt; p.Key, p =&gt; p.ToList());</pre><p> 我被困在這一點上,你有什么想法我該怎么做嗎?</p></div></object></enum,> 基於RadioButton的C#WPF篩選器組合框 ASP.NET C#-未將RadioButtons分組
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM