【发布时间】:2023-01-19 12:43:59
【问题描述】:
我已经设法获得了一个单选按钮组功能,可以使用以下 XAML:
<ScrollView>
<ListView ItemsSource="{Binding Devices}"
Style="{StaticResource ListViewSimpleStyle}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell x:DataType="local:DeviceEntryModel">
<RadioButton IsChecked="{Binding IsChecked, Mode=TwoWay}"
GroupName="Devices">
<RadioButton.Content>
<Label BindingContext="{Binding Source={RelativeSource AncestorType={x:Type RadioButton}}, Path=BindingContext}"
Text="{Binding Name}"
IsEnabled="{Binding Source={RelativeSource AncestorType={x:Type RadioButton}}, Path=IsEnabled}" />
</RadioButton.Content>
</RadioButton>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollView>
有什么方法可以简化它并使其更易于重用吗?我在想最终结果是这样的:
<RadioButtonGroupView ItemSource="{Binding Devices}">
<RadioButtonGroupView.ItemTemplate>
<RadioButton IsChecked="{Binding IsChecked, Mode=TwoWay}"
x:DataType="local:Device"
GroupName="Devices">
<Label BindingContext="{Binding Source={RelativeSource AncestorType={x:Type RadioButton}}, Path=BindingContext}"
Text="{Binding Name}"
IsEnabled="{Binding Source={RelativeSource AncestorType={x:Type RadioButton}}, Path=IsEnabled}" />
</RadioButton>
</RadioButtonGroupView.ItemTemplate>
</RadioButtonGroupView>
沿着这些思路,更简单的东西,你明白了要点。谢谢!
我尝试了一些具有可绑定属性的东西,但不确定这是正确的方法。
【问题讨论】:
-
删除
ScrollView。ListView已经可以滚动了。一旦你做了那个改变,你的原始版本和你的“更可重用”的版本之间就没有重要的区别了;您刚刚将ListView替换为RadioButtonGroupView。如果您真的想制作可重用控件,请查找创建“自定义控件”的示例。重要的是,了解BindableProperty,它是将值从周围页面传递到自定义控件所必需的。这就是使自定义控件有用的原因。