Skip to content

Instantly share code, notes, and snippets.

@Unril
Created May 15, 2013 12:37
Show Gist options
  • Save Unril/5583690 to your computer and use it in GitHub Desktop.
Save Unril/5583690 to your computer and use it in GitHub Desktop.
RadioButtonBinder
public static class RadioButtonBinder {
public static readonly DependencyProperty ValueProperty =
DependencyProperty.RegisterAttached("Value", typeof (object), typeof (RadioButtonBinder),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.NotDataBindable, ValueChanged));
public static readonly DependencyProperty BindProperty =
DependencyProperty.RegisterAttached("Bind", typeof (object), typeof (RadioButtonBinder),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, BindChanged));
private static bool _react = true;
private static void ValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) {
((RadioButton) obj).Checked += (sender, eventArgs) => {
if (_react) {
var btn = (RadioButton) sender;
SetBind(btn, GetValue(btn));
}
};
}
private static void BindChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) {
var btn = (RadioButton) obj;
if (Equals(GetValue(btn), args.NewValue)) {
_react = false;
btn.IsChecked = true;
_react = true;
}
}
public static void SetValue(RadioButton element, object value) {
element.SetValue(ValueProperty, value);
}
public static object GetValue(RadioButton element) {
return element.GetValue(ValueProperty);
}
public static void SetBind(RadioButton element, object value) {
element.SetValue(BindProperty, value);
}
public static object GetBind(RadioButton element) {
return element.GetValue(BindProperty);
}
}
<StackPanel Margin="0,0,0,13">
<RadioButton Content="{x:Static infrastructure:ConversionTypes.CompressedRle}"
IsChecked="True"
Margin="0,0,0,5"
c:RadioButtonBinder.Bind="{Binding Project.ConversionType}"
c:RadioButtonBinder.Value="{Binding Encoders[0].Description}" />
<RadioButton Content="{x:Static infrastructure:ConversionTypes.Uncompressed}"
c:RadioButtonBinder.Bind="{Binding Project.ConversionType}"
c:RadioButtonBinder.Value="{Binding Encoders[1].Description}" />
</StackPanel>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment