问题
I have a master-detail wpf application. The "master" is a datagrid , and "detail" is two radio buttons. Based on the row selection the radio buttons are checked in the "detail" section.
I am binding my Radio button the following way using a inttoboolean converter. xaml :
<StackPanel Margin="2">
<RadioButton Margin="0,0,0,5" Content="In Detail" IsChecked="{Binding Path=itemselect.OutputType, Converter ={StaticResource radtointOTSB}, ConverterParameter= 0}"/>
<RadioButton Content="In Breif" IsChecked="{Binding Path=itemselect.OutputType, Converter ={StaticResource radtointOTSB}, ConverterParameter= 1}"/>
</StackPanel>
In the View Model:
public class radtointOTSB : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int OTint = Convert.ToInt32(value);
if (OTint == int.Parse(parameter.ToString()))
return true;
else
return false;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return parameter;
}
}
My implementation works well for the first few selections in datagrid. And all of a sudden , neither of my radio button is selected.
I have no clue on why it happens, any suggestion is welcomed.
Thanks in advance.
回答1:
Search for problems with Binding multiple RadioButtons - there are enough complaints out there. Basically the binding won't receive the value of False because it not being passed to the Dependency Property..etc etc
Try using the following class instead of the regular RadioButton, bind to IsCheckedExt, as it forces the checkbox's IsChecked value to update.
public class RadioButtonExtended : RadioButton
{
public static readonly DependencyProperty IsCheckedExtProperty =
DependencyProperty.Register("IsCheckedExt", typeof(bool?), typeof(RadioButtonExtended),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsCheckedRealChanged));
private static bool _isChanging;
public RadioButtonExtended ()
{
Checked += RadioButtonExtendedChecked;
Unchecked += RadioButtonExtendedUnchecked;
}
public bool? IsCheckedExt
{
get { return (bool?)GetValue(IsCheckedExtProperty); }
set { SetValue(IsCheckedExtProperty, value); }
}
public static void IsCheckedRealChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
_isChanging = true;
((RadioButtonExtended)d).IsChecked = (bool)e.NewValue;
_isChanging = false;
}
private void RadioButtonExtendedChecked(object sender, RoutedEventArgs e)
{
if (!_isChanging)
IsCheckedExt = true;
}
private void RadioButtonExtendedUnchecked(object sender, RoutedEventArgs e)
{
if (!_isChanging)
IsCheckedExt = false;
}
}
来源:https://stackoverflow.com/questions/10452009/radiobutton-wpf-binding