WPF RadioButton 绑定Int值

时间:2024-10-24 14:28:30
public class FlowModeToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter is string paramString && int.TryParse(paramString, out int paramInt))
        {
            return value is int selectedValue && selectedValue == paramInt;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool isChecked && isChecked && parameter is string paramString && int.TryParse(paramString, out int paramInt))
        {
            return paramInt;
        }
        return -1; // 或者根据需要返回其他默认值
    }
}
<hc:ButtonGroup Width="460" Margin="10,0">
    <RadioButton Content="1" IsChecked="{Binding FlowMode, Converter={StaticResource FlowModeToBoolConverter}, ConverterParameter=0}" />
    <RadioButton Content="2" IsChecked="{Binding FlowMode, Converter={StaticResource FlowModeToBoolConverter}, ConverterParameter=1}" />
    <RadioButton Content="3" IsChecked="{Binding FlowMode, Converter={StaticResource FlowModeToBoolConverter}, ConverterParameter=2}" />
    <RadioButton Content="1" IsChecked="{Binding FlowMode, Converter={StaticResource FlowModeToBoolConverter}, ConverterParameter=3}" />
    <RadioButton Content="2" IsChecked="{Binding FlowMode, Converter={StaticResource FlowModeToBoolConverter}, ConverterParameter=4}" />
    <RadioButton Content="3" IsChecked="{Binding FlowMode, Converter={StaticResource FlowModeToBoolConverter}, ConverterParameter=5}" />
</hc:ButtonGroup>

相关文章