StackPanel
列挙型の値に対応するRadioButton
オブジェクトをに入力したいと思います。各ボタンのハンドラーは、対応する列挙型 val を取る任意の計算を実行する必要があります。
これが私が思いついた方法です:
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
、 enum に s が必要だとしFigureHorizontalAnchor
ます。各ボタンのアクションで、呼び出されHorizontalAnchor
た特定のプロパティを設定したいと思います。呼び出す方法は次のとおりです。Figure
figure
EnumToRadioButtonPanel
var figure = new Figure();
var stackPanel = new StackPanel();
EnumToRadioButtonPanel(stackPanel, typeof(FigureHorizontalAnchor),
val =>
{
figure.HorizontalAnchor = (FigureHorizontalAnchor)
Enum.ToObject(typeof(FigureHorizontalAnchor), val);
});
私の質問は、これを達成するためのより良い方法はありますか? 代わりに「バインディング」手法を使用する必要がありますか? RadioButton
ここで SO に関するいくつかの関連する質問を見てきましたが、XAML で s をレイアウトする必要がありました。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);
}
}
}