Wpf – Databind radiobutton group to property

data-bindingwpfxaml

I have a radiobutton group:

<TextBlock Height="24" Text="Update Interval (min):"/>
<RadioButton x:Name="radioButtonTimerNone" IsChecked="{Binding UpdateInterval, Converter={StaticResource updateIntervalToCheckedConverter}, Mode=TwoWay}"} Content="None" />
<RadioButton x:Name="radioButtonTimerOne" IsChecked="{Binding UpdateInterval, Converter={StaticResource updateIntervalToCheckedConverter}, Mode=TwoWay}" 
                Content="1" />
<RadioButton x:Name="radioButtonTimerFive" IsChecked="{Binding UpdateInterval, Converter={StaticResource updateIntervalToCheckedConverter}, Mode=TwoWay}" 
                Content="5" />

And a property:

    public int UpdateInterval {
        get { return _updateInterval; }
        set { _updateInterval = value;
            onPropertyChanged("UpdateInterval");
        }
    }

How do I bind the radiobuttons to the property, so radioButtonTimerNone is checked when UpdateInterval is 0, radioButtonTimerOne is checked when UpdateInterval is 1, etc.
I have tried to create a converter, but it doesn't identify which rb is being set:

[ValueConversion(typeof(RadioButton), typeof(bool))] 
class UpdateIntervalToCheckedConverter : System.Windows.Data.IValueConverter
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

I expected 'value' to be a radiobutton, but it appears to be the value of UpdateInterval.

Thanks for any hints…

Best Answer

If you are using MVVM and are bound to a ViewModel (I would guess that you are), I usually consider my ViewModel to be a big ValueConverter. Why not put that logic into properties for each?

Here's an example of one of them:

public bool Timer5Enabled
{
     get { return UpdateInterval == 5; }
}

And then you'd just bind to that:

<RadioButton
    x:Name="radioButtonTimerOne"
    IsChecked="{Binding Timer5Enabled, Mode=OneWay}"
    Content="1" />

The only thing you'd need to change would be to tie your interval update logic to raise OnChanged for your dependent properties:

public int UpdateInterval {
        get { return _updateInterval; }
        set { _updateInterval = value;
            onPropertyChanged("UpdateInterval");
            onPropertyChanged("Timer5Enabled");
            onPropertyChanged("...");
        }
    }

ValueConverters are good to avoid if you can.

Related Topic