模型
public class people { public string name{get;set;} public bool? sex{get;set;} }
转换器
namespace Helper { public class StringRadioConvert : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null || parameter == null) return false; string checkvalue = value.ToString(); string targetvalue = parameter.ToString(); bool r = checkvalue.Equals(targetvalue, StringComparison.InvariantCultureIgnoreCase); return r; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || parameter == null) return null; bool usevalue = (bool)value; if (usevalue) return parameter.ToString(); return null; } } /// <summary> /// BOOL TO BOOL /// </summary> public class BoolRadioConvert : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null || parameter == null) return false; bool flag = (bool)value; if ((flag && (string)parameter == "男") || (!flag && (string)parameter == "女")) { return true; } return false; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || parameter == null) return null; bool usevalue = (bool)value; if (!usevalue) return null; Dictionary<string, bool> dict = new Dictionary<string, bool>(); dict.Add("男", true); dict.Add("女", false); return dict[parameter.ToString()]; } } }
VIEW
<UserControl ...... xmlns:helper="clr-namespace:Helper"......> <UserControl.Resources> <helper:StringRadioConvert x:Key="radioStringConverter" /> <helper:BoolRadioConvert x:Key="radioBoolConverter" /> </UserControl.Resources> <Label VerticalAlignment="Center" HorizontalAlignment="Right" FontWeight="ExtraBlack">用户:</Label> <RadioButton Content="小陈" GroupName="SeatGroup" IsChecked="{Binding people.name, Converter={StaticResource radioStringConverter}, ConverterParameter='小陈'}"></RadioButton> <RadioButton Content="小李" GroupName="SeatGroup" IsChecked="{Binding people.name, Converter={StaticResource radioStringConverter}, ConverterParameter='小李'}" ></RadioButton> <Label VerticalAlignment="Center" HorizontalAlignment="Right" FontWeight="ExtraBlack">输血史:</Label> <RadioButton Margin="4 0" GroupName="TransfusionGroup" IsChecked="{Binding people.sex , Converter={StaticResource radioBoolConverter}, ConverterParameter='男'}">男</RadioButton> <RadioButton Margin="4 0" GroupName="TransfusionGroup" IsChecked="{Binding people.sex , Converter={StaticResource radioBoolConverter}, ConverterParameter='女'}">女</RadioButton> </UserControl>
解析:
name为string类型,转化为bool
sex需定义为bool?类型,否则会出现红框提示,此外,IsChecked是无法直接绑定变量的
时间: 2024-11-06 07:25:15