Xamarin.Forms 从SQL加载的对象数据无法填充RadioButton问题咨询
根因分析
你遇到的问题核心是RadioButton的Value值类型和绑定的FlowType属性类型不匹配,这是Xamarin.Forms中RadioButtonGroup回显异常的最常见诱因:
你手动构造Category对象时,给FlowType赋的是字符串类型的值(FlowType = "1"),和XAML中写死的RadioButton的Value("0"、"1"、"2",默认是字符串类型)类型一致,相等判断成立,所以能正常回显。
而从SQL数据库读取数据时,ORM默认会把数据库中数值类型的字段(比如int、tinyint、char等)映射为C#的数值类型,或者如果数据库字段是char(1)类型,读取出来的字符串可能携带末尾空格,导致和XAML中的字符串Value匹配失败,无法触发选中状态。
解决方案
方案1:统一类型(推荐)
把RadioButton的Value显式声明为数值类型,和FlowType属性、数据库字段类型保持一致:
<StackLayout Orientation="Horizontal" RadioButtonGroup.GroupName="TEST" RadioButtonGroup.SelectedValue="{Binding ChosenObject.FlowType, Mode=TwoWay}"> <RadioButton Content="Op 1" Value="{x:Int 0}" /> <RadioButton Content="Op 2" Value="{x:Int 1}" /> <RadioButton Content="Op 3" Value="{x:Int 2}" /> </StackLayout>
同时确保Category类的FlowType属性定义为int类型,数据库对应字段也设置为int/tinyint类型即可。
方案2:处理字符串匹配问题
如果FlowType必须是字符串类型,你需要检查从数据库读取的FlowType值是否携带空白字符,赋值前做一次修剪:
// 从数据库读取后处理 var c = await database.GetAllCategories(); foreach(var category in c) { category.FlowType = category.FlowType?.Trim(); } Categories = new ObservableCollection<Category>(c);
补充验证方案
如果上述方案都无效,可以在SecondPage加一个临时Label调试,确认FlowType的值是否符合预期:
<!-- 加入到SecondPage的StackLayout中,调试完可以删掉 --> <Label Text="{Binding ChosenObject.FlowType}" /> <Label Text="{Binding Source={x:Reference Radio0}, Path=Value}" x:Name="Radio0Label"/> <RadioButton Content="Op 1" Value="0" x:Name="Radio0" />
运行后看两个Label显示的文本和类型是否完全一致,就能快速定位匹配失败的原因。
内容的提问来源于stack exchange,提问作者Bumbar
相关产品推荐
相关产品推荐

