none
Databinding enum to radiobuttons

    Question

  • I have an enum I am trying to databind five radio buttons to.

    Here is the enum:
    public enum Testing
    {
         test1,
         test2,
         test3,
         test4,
         test5
    }

    Here is the property I'm trying to bind to:
    public Testing TestEnumBinding {get;set;}

    Here is the xaml:

     

     

    <RadioButton x:Name="rbTest1" GroupName="Test1" HorizontalAlignment="Left" Margin="30,0.219,0,0" VerticalAlignment="Top" Content="Test1" IsChecked="{Binding Path=Testing, Mode=TwoWay, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=Test1}" Height="13.277" Width="124.69" Grid.Row="1" />

     

     

    <RadioButton x:Name="rbTest2" GroupName="Test2" Margin="30,20.219,0,14" Content="Test2" HorizontalAlignment="Left" IsChecked="{Binding Path=Testing, Mode=TwoWay, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=Test2}" Width="112.933" Grid.Row="1" />

     

     

    <RadioButton x:Name="rbTest3" GroupName="Test3" HorizontalAlignment="Left" Margin="30,0,0,7.504" Content="Test3" IsChecked="{Binding Path=Testing, Mode=TwoWay, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=Test3}" Width="90.987" Height="13.496" VerticalAlignment="Bottom" />

     

     

    <RadioButton x:Name="rbTest4" GroupName="Test4" Margin="29.567,0,0,29.723" VerticalAlignment="Bottom" Content="Test4" HorizontalAlignment="Left" IsChecked="{Binding Path=Testing, Mode=TwoWay, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=Test4}" Height="13.277" Width="112.933" />

     

     

    <RadioButton x:Name="rbTest5" GroupName="Test5" Margin="30,24,0,0" Content="Test5" HorizontalAlignment="Left" IsChecked="{Binding Path=Testing, Mode=TwoWay, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=Test5}" Width="112.933" Height="13.277" VerticalAlignment="Top" />

    Here is the value converter:

    public

     

    class EnumBooleanConverter : IValueConverter

    {

    #region

     

    IValueConverter Members

     

     

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

     

    string ParameterString = parameter as string;

     

     

    if (ParameterString == null)

     

    return DependencyProperty.UnsetValue;

     

     

    if (Enum.IsDefined(value.GetType(), value) == false)

     

    return DependencyProperty.UnsetValue;

     

     

    object paramvalue = Enum.Parse(value.GetType(), ParameterString);

     

     

    if (paramvalue.Equals(value))

     

    return true;

     

    else

     

    return false;

    }

     

     

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

     

    string ParameterString = parameter as string;

     

     

    if (ParameterString == null)

     

    return DependencyProperty.UnsetValue;

     

    return Enum.Parse(targetType, ParameterString);

    }

    #endregion

    }

    However, on the UI, when I select a radio button, the one that was previously selected remains selected and I have two radio buttons selected. This happens because they are in different groups and aren't mutually exclusive. However, they must be in different groups in order for the binding to remain. How can I alter my converter or other code in order to correctly handle this situation? Can it be done?

    Thursday, October 22, 2009 5:31 PM

Answers

  • Hi,

    How do you get the Input instance? I try with the following code and it works fine.

      private void button1_Click(object sender, RoutedEventArgs e)
            {
                Input t = this.FindResource("InputDataSource") as Input;
                t.Testing = Testing.test2;
            }

    Best Regards,
    Zhi-Xin


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework!
    • Marked as answer by BBauer42 Wednesday, October 28, 2009 12:32 PM
    Wednesday, October 28, 2009 8:26 AM

All replies

  • Use ObjectDataProvider. Like so:


    <Window x:Class="MSDNTest.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:MSDNTest"
        Title="Window1" Height="600" Width="600">
    
        <Window.Resources>
            <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="TestingDataProvider">
                <ObjectDataProvider.MethodParameters>
                    <x:Type Type="{x:Type local:Testing}"/>
                </ObjectDataProvider.MethodParameters>
            </ObjectDataProvider>
        </Window.Resources>
        <StackPanel>
            <ItemsControl ItemsSource="{Binding Source={StaticResource TestingDataProvider}}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <RadioButton GroupName="Testing" Content="{Binding}" />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
    </Window>

    using System.Windows;
    
    namespace MSDNTest
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
            }
        }
    
        public enum Testing
        {
            test1,
            test2,
            test3,
            test4,
            test5
        }
    }

    Bigsby, Lisboa, Portugal
    O que for, quando for, é que será o que é...
    Wenn ist das Nunstruck git und Slotermeyer? Ja! ... Beiherhund das Oder die Flipperwaldt gersput!
    http://bigsby.eu
    • Marked as answer by Zhi-Xin Ye Tuesday, October 27, 2009 10:22 AM
    • Unmarked as answer by BBauer42 Tuesday, October 27, 2009 3:19 PM
    Thursday, October 22, 2009 10:56 PM
  • That makes the radio buttons mutually exclusive. However, when a button is selected my public Testing TestEnumBinding property is not being updated. Also, I cannot specify which radio button I want selected to begin with. What if I want test4 selected to start? I don't want to say IsChecked = True, I want to set the property.
    Tuesday, October 27, 2009 3:21 PM
  • Here is what I have so far:

    namespace RadioBindingToEnum
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
                Input input = new Input();
    
                input.Testing = Testing.test2;
       
            }
        }
    }
    That should set my second radio button to be selected by default but it does not.

    Here is the Input class:
    using System;
    using System.ComponentModel;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    
    namespace RadioBindingToEnum
    {
        public enum Testing
        {
            test1,
            test2,
            test3,
        }
    
        class Input : INotifyPropertyChanged
        {
            #region Properties
    
            public Testing Testing 
            {
                get { return _testing; }
                set
                {
                    _testing = value;
                    Console.WriteLine(_testing);
                    OnPropertyChanged("Testing");
                }
            }private Testing _testing;
    
            #endregion
    
            #region INotifyPropertyChanged Members
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            void OnPropertyChanged(string propName)
            {
                if (this.PropertyChanged != null)
                    this.PropertyChanged(
                        this, new PropertyChangedEventArgs(propName));
            }
            #endregion
        }
    
        public class EnumBooleanConverter : IValueConverter
        {
            #region IValueConverter Members
    
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var ParameterString = parameter as string;
    
                if (ParameterString == null)
                    return DependencyProperty.UnsetValue;
    
                if (Enum.IsDefined(value.GetType(), value) == false)
                    return DependencyProperty.UnsetValue;
    
                object paramvalue = Enum.Parse(value.GetType(), ParameterString);
    
                if (paramvalue.Equals(value))
                    return true;
                else
                    return false;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var ParameterString = parameter as string;
    
                if (ParameterString == null)
                    return DependencyProperty.UnsetValue;
    
                return Enum.Parse(targetType, ParameterString);
            }
    
            #endregion
        }
    }
    I know thing are working b/c in the debug window I see what is being written from this line: Console.WriteLine(_testing);
    in the Testing property.

    And finally here is the XAML:
    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:RadioBindingToEnum"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" x:Class="RadioBindingToEnum.Window1"
        Title="Window1" Height="300" Width="300" mc:Ignorable="d">
        <Window.Resources>
            <local:Input x:Key="InputDataSource" d:IsDataSource="True"/>
            <local:EnumBooleanConverter x:Key="EnumBooleanConverter"/>
        </Window.Resources>
        <Grid DataContext="{Binding Source={StaticResource InputDataSource}}">
            <RadioButton 
                x:Name="rbTest1" 
                GroupName="Test1" 
                Margin="10,0,0,0" 
                Content="Test1" 
                IsChecked="{Binding Path=Testing, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=test1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="56" Height="20" />
            <RadioButton 
                x:Name="rbTest2" 
                GroupName="Test2" 
                Margin="70,0,0,0" 
                Content="Test2" 
                IsChecked="{Binding Path=Testing, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=test2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="48" Height="20" />
            <RadioButton 
                x:Name="rbTest3" 
                GroupName="Test3" 
                Margin="131,0,104,0" 
                Content="Test3" 
                IsChecked="{Binding Path=Testing, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=test3, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Height="20"  />
        </Grid>
    </Window>
    I have only one problem now. Why doesn't this line of code set the second radio button to be selected? The binding mode is TwoWay so it should work.

     input.Testing = Testing.test2;
    Tuesday, October 27, 2009 3:40 PM
  • Hi,

    How do you get the Input instance? I try with the following code and it works fine.

      private void button1_Click(object sender, RoutedEventArgs e)
            {
                Input t = this.FindResource("InputDataSource") as Input;
                t.Testing = Testing.test2;
            }

    Best Regards,
    Zhi-Xin


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework!
    • Marked as answer by BBauer42 Wednesday, October 28, 2009 12:32 PM
    Wednesday, October 28, 2009 8:26 AM
  • THANKS!!! Works great... I was not getting the instance that way.

    Wednesday, October 28, 2009 12:32 PM
  • How do you get the instance when there is not a seperate datasource? For example, when the DataContext of the page is just going to be "this" ?

    I have done something similar to above, but it seems again I do not have the correct instance. Thanks.
    Thursday, November 19, 2009 3:22 PM
  • How do you set up the binding? Please show me the code you used.



    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework!
    Friday, November 20, 2009 2:56 AM