问题描述
为了清楚起见,我在这里谈论的是2006年Xamarin 4.6发行的RadioButton。
我在这里的目的是创建一个绑定,该绑定将与同一组中的多个RadioButton一起使用。最终,我可以离开屏幕返回到它并设置最后选择的RadioButton项。
因此,我知道您可以为IsChecked
属性设置一个false属性的true绑定。但是,这一项没有上下文。
我知道您还可以为页面或控件设置绑定上下文...所以我想我可以为其中的所有项目设置一个StackLayout上下文...但这仍然无济于事。
这就像我想要实现的...是的,我不会准确地拥有10个,我只是想指出一点,我不想使用很多不同的绑定。.
<RadioButton GroupName="Numbers" Text="One"
IsChecked="{Binding IsCheckednumbersgroup}" />
<RadioButton GroupName="Numbers" Text="Two"
IsChecked="{Binding IsCheckednumbersgroup}" />
....
<RadioButton GroupName="Numbers" Text="Ten"
IsChecked="{Binding IsCheckednumbersgroup}" />
解决方法
如果我们将同一源与多个 RadioButton 绑定在一起,则会导致出现问题,因为当您单击其中一个时,其他RadioButton也将受到影响。
因此,在您的情况下,如果您不想定义多重属性,则可以定义一个List并将它们与项目绑定。
在Xaml中
命令下,在选择了单选按钮时执行。
<RadioButton GroupName="Numbers" Text="One" IsChecked="{Binding MySource[0]}" Command="{Binding ButtonCommand}" CommandParameter="0" />
<RadioButton GroupName="Numbers" Text="Two" IsChecked="{Binding MySource[1]}" Command="{Binding ButtonCommand}" CommandParameter="1" />
<RadioButton GroupName="Numbers" Text="Three" IsChecked="{Binding MySource[2]}" Command="{Binding ButtonCommand}" CommandParameter="2" />
在ViewModel中
public ObservableCollection<bool> MySource { get; set; }
public xxxViewModel()
{
MySource = new ObservableCollection<bool>() {true,false,false };
ButtonCommand = new Command((org)=> {
var index = int.Parse(org.ToString());
App.Current.MainPage.DisplayAlert("Title","the status of RadioButton"+(index+1).ToString()+"is"+MySource[index].ToString(),"OK");
});
}