Ответ 1
Вы можете сделать такую вещь очень динамичной с использованием шаблонов данных, например.
(- Изменить:. Намного больше смысла использовать ListBox
, у которого уже есть свойство SelectedItem
, см. этот пересмотренный ответ -)
public partial class MainWindow : Window, INotifyPropertyChanged
{
//For simplicity in put everything in the Window rather than models and view-models
public enum TestEnum { Ichi, Ni, San }
private TestEnum _EnumValue;
public TestEnum EnumValue
{
get { return _EnumValue; }
set
{
if (_EnumValue != value)
{
_EnumValue = value;
PropertyChanged.Notify(() => this.EnumValue);
}
}
}
//...
}
<ItemsControl>
<ItemsControl.Resources>
<!-- Gets the enum values -->
<ObjectDataProvider x:Key="items" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MainWindow+TestEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<!-- A MultiValueConverter which compares for equality -->
<vc:EqualityComparisonConverter x:Key="eqc" />
</ItemsControl.Resources>
<ItemsControl.ItemsSource>
<Binding Source="{StaticResource items}" />
</ItemsControl.ItemsSource>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding}" GroupName="TestEnumGroup"
Command="{x:Static local:Commands.DoStuff}" CommandParameter="{Binding}">
<RadioButton.IsChecked>
<MultiBinding Converter="{StaticResource eqc}" Mode="OneWay">
<!-- This should point to the viewmodel enum property -->
<Binding ElementName="Window" Path="DataContext.EnumValue" />
<!-- This passes the DataContext, the enum value behind the templated item, to the converter -->
<Binding />
</MultiBinding>
</RadioButton.IsChecked>
</RadioButton>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
private void DoStuff_Executed(object sender, ExecutedRoutedEventArgs e)
{
TestEnum enumval = (TestEnum)e.Parameter;
EnumValue = enumval;
}
Это работает с необработанными значениями enum, вы можете увеличить их с помощью отображаемых строк, используя атрибуты.
Поскольку IsChecked
привязан ко всем радиобарабанам, RadioButton.GroupName
становится избыточным.
(Я не представил свою реализацию EqualityComparisonConverter
, потому что это, вероятно, дерьмо, это не должно быть слишком сложно, чтобы правильно реализовать его, хотя)