【问题标题】:Xamarin: Binding grouped RadioButton isChecked property with a viewModelXamarin:将分组的 RadioButton isChecked 属性与 viewModel 绑定
【发布时间】:2021-06-13 06:56:31
【问题描述】:

为了清楚起见,我在这里谈论的是 2006 年与 Xamarin 4.6 一起发布的 RadioButton

我的目标是创建一个绑定,它可以与同一组中的多个 RadioButtons 一起使用。最终,我可以离开我的屏幕并返回并设置最后选择的 RadioButton 项。

所以我知道您可以为 IsChecked 属性设置 true 或 false 属性绑定。但是,这个单个项目没有它是哪个项目的上下文。

我知道您还可以为页面或控件设置绑定上下文...所以我想我可以为其中的所有项目设置一个 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}" />

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    如果我们用多个RadioButton绑定同一个源,会导致当你点击其中一个时,其他RadioButton也会受到影响。

    所以在你的情况下,如果你不想定义多属性,你可以定义一个 List 并将它们与项目绑定。

    在 Xaml 中

    Command,当 RadioButton 被选中时执行。

    <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" />
    

    在视图模型中

    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");
    
                });
    
            }
    

    【讨论】:

    • Xamarin 5.0,我们没有单选按钮的“命令”属性。有没有其他选择?
    • 是的,他们还删除了 text 道具,至少可以说是奇怪的
    猜你喜欢
    • 2011-06-16
    • 2021-05-24
    • 2014-04-19
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多