如何在xamarin表单中使用单选按钮

时间:2017-05-23 19:37:50

标签: xamarin xamarin.forms

创建注册页面我需要从用户那里获取以下数据。 -名字 -姓 -用户名 -电子邮件 -密码 -出生日期 - 的性别 - 用户角色

For Last to parameters我无法找到如何在xamarin表单中使用单选按钮。以下是我的注册页面代码。

<StackLayout BackgroundColor="#30af91" Padding="60">


<Entry Text="{Binding FirstName}" Placeholder="First Name"/>
<Entry Text="{Binding LastName}" Placeholder="Last Name"/>
<Entry Text="{Binding UserName}" Placeholder="Last Name"/>
<Entry Text="{Binding Email}" Placeholder="Email" />
<Entry Text="{Binding Password}" Placeholder="Password" IsPassword="True"/>
<Entry Text="{Binding ConfirmPassword}" Placeholder="Confirm Password" IsPassword="True"/>
<DatePicker MinimumDate="1/1/1948" MaximumDate="12/31/2007"/>


<!--Radio buttons for Gender
    1. Male   2.Female-->

<!--Radio Buttons for UserRole
    1. Admin  2.Participant-->

<Button Command="{Binding RegisterCommand}" Text="Register"/>
<Label Text="{Binding Message}" />


</StackLayout>

12 个答案:

答案 0 :(得分:5)

我认为有一个更简单的解决方案,它相当容易并且不需要库。确实,一个广播组只是一个精美的ListView。您只需要为每个具有IsSelected标志的单选按钮创建一个viewModel并在2张图像之间切换。我需要允许用户选择令牌保留的时间:

XAML

<ListView
    HasUnevenRows="True"
    HorizontalOptions="FillAndExpand"
    ItemsSource="{Binding Durations}"
    ItemSelected="ListView_ItemSelected"
    SelectedItem="{Binding SelectedDuration}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout
                    Orientation="Horizontal">
                    <Image
                        HeightRequest="18"
                        IsVisible="{Binding IsSelected}"
                        Source="radioButtonChecked.png"
                        WidthRequest="18"/>
                    <Image
                        HeightRequest="18"
                        IsVisible="{Binding IsUnselected}"
                        Source="radioButtonUnchecked.png"
                        WidthRequest="18"/>
                    <Label
                        Margin="8,0,0,0"
                        Text="{Binding Caption}"/>
                </StackLayout>
            </ViewCell>
         </DataTemplate>
      </ListView.ItemTemplate>
   </ListView>

我们在内容页面中创建一个列表视图,并监听ItemSelected事件。每个列表项都是一个水平堆栈面板,我们可以根据所选状态在两张图像之间翻转

隐藏代码

public partial class LoginPage : ContentPage
{
    LoginPageViewModel LoginPageViewModel { get; }

    public LoginTwoFactorFrequencyPage ()
    {
        BindingContext = LoginPageViewModel = new LoginPageViewModel();

        InitializeComponent ();
    }

    private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        LoginPageViewModel.UpdateSelected(e.SelectedItem as PersistenceDuration);
    }
}
  • 页面后面的代码实例化视图模型,并使用页面视图模型上新选择的项目调用UpdateSelected方法*

RadioButton ViewModel

每个单选按钮的视图模型:

public class PersistenceDuration : ViewModelBase
{
    bool isSelected;

    public string Caption { get; set; }
    public TwoFactorTokenPersistenceDuration Duration { get; set; }
    public bool IsSelected
    {
        get => isSelected;
        set
        {
            isSelected = value;
            OnPropertyChanged();
            OnPropertyChanged("IsUnselected");
        }
    }
    public bool IsUnselected => !IsSelected;

    public PersistenceDuration(string caption, TwoFactorTokenPersistenceDuration duration)
    {
        Caption = caption;
        Duration = duration;
        IsSelected = false;
    }
}

单选按钮视图模型包含选择信息和标题。我们确保每当选定状态更改时都触发OnPropertyChanged

页面ViewModel

public class LoginPageViewModel : ViewModelBase
{
    PersistenceDuration duration;
    PersistenceDuration selectedDuration;

    public ObservableCollection<PersistenceDuration> Durations { get; }
    public PersistenceDuration SelectedDuration
    {
        get => selectedDuration;
        set
        {
            if (value != null)
            {
                duration = value;
                UpdateSelected(duration);
            }
            OnPropertyChanged();
        }
    }

    public LoginTwoFactorFrequencyViewModel()
    {
        Durations = new ObservableCollection<PersistenceDuration>(
            new List<PersistenceDuration>()
            {
                new PersistenceDuration(AppResources.Save_code__forever, TwoFactorTokenPersistenceDuration.Forever),
                new PersistenceDuration(AppResources.ChatRequireEvery30Days, TwoFactorTokenPersistenceDuration.ThirtyDays),
                new PersistenceDuration(AppResources.ChatRequireEveryLogin, TwoFactorTokenPersistenceDuration.None),
            });
    }

    public void UpdateSelected(PersistenceDuration persistenceDuration)
    {
        foreach (var item in Durations)
            item.IsSelected = persistenceDuration == item;
    }
}

在页面视图模型中,我们创建XAML绑定到的单选按钮视图模型的列表。当我们UpdateSelected()时,所有IsSelected状态都会更新,从而触发绑定更新,从而翻转图像。

当某人选择某项时,您仍然需要对突出显示做一些事情,但这很容易在互联网上找到:)

答案 1 :(得分:3)

您可以使用管理NuGets包中的XLabs插件。安装后你可以这样使用:

在Xaml中:

controls:BindableRadioGroup x:Name="Radiobtn"

在C#中:

string[] gender = {"MAlE","FEMALE"}
Radiobtn.Add(gender)

参考链接
https://github.com/XLabs/Xamarin-Forms-Labs/tree/master/samples/XLabs.Samples/XLabs.Samples/Pages/Controls

答案 2 :(得分:2)

Xamarin表单不提供单选按钮。

您可以使用

<强> 1)Switch

<强> 2)Picker

或满足您要求的任何其他组件

答案 3 :(得分:1)

您可以将图像用作单选按钮。当你点击它时,它可以改变。虽然这不是一个好方法。 这是xaml代码:

<Image  Scale="0.7"  HorizontalOptions="Start" x:Name="radioButton" Source="unRadioBtn.png">
                    <Image.GestureRecognizers>
                        <TapGestureRecognizer Tapped="radioButton_Clicked"></TapGestureRecognizer>
                    </Image.GestureRecognizers>
                </Image>

这是.cs:

 private void radioButton_Clicked(object sender, EventArgs e)
    {
        radioButton.Source = "radioBtn.png";
    }

答案 4 :(得分:1)

如果你想要真正的无线电按钮,你可以xlabs他们的包(https://github.com/XLabs/Xamarin-Forms-Labs/tree/master/src/Forms/XLabs.Forms/Controls/RadioButton

就我个人而言,我只是使用了一个选择器,Xlabs软件包暂时没有更新,所以它们可能是radiobutton中的一些错误

答案 5 :(得分:1)

不带包装即可获得单选按钮效果。将标签与文本unicode圆圈\u26AA\u25CB一起使用。在每个标签上附加一个标签手势识别器。

点击后,将所选按钮的文本更改为unicode圆圈项目符号\u29BF,并将其他按钮的文本更改回unicode圆圈\u26AA

在您喜欢的平台上进行测试,因为每个平台的显示可能有所不同。更改文本时,可能需要调整字体大小。

答案 6 :(得分:1)

您可以将Plugin.InputKit用于单选按钮。

对于静态源:

            <input:RadioButtonGroupView>
                <input:RadioButton Text="Option 1" />
                <input:RadioButton Text="Option 2" />
                <input:RadioButton Text="Option 3" />
                <input:RadioButton Text="Option 4" />
            </input:RadioButtonGroupView>


对于动态源:


        <input:SelectionView SelectionType="RadioButton" ItemsSource="{Binding MyItemsList}" />

设置说明文档here

答案 7 :(得分:1)

Xamarin.Forms 4.6引入了新的library(egg) p <- ggplot(mtcars, aes(mpg, wt)) p <- p + geom_point() p <- p + facet_grid(gear ~ cyl) p <- tag_facet(p) ggsave('test.tiff', p, dpi = 500) 控件。您可以在这里找到文档:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/radiobutton

答案 8 :(得分:0)

您可以使用switch component。您还可以看到XLabs project中已取消的复选框组件的实现,获取代码并根据需要进行修改。

提示:您需要每个平台的自定义渲染器才能工作。

答案 9 :(得分:0)

您需要使用Picker https://developer.xamarin.com/api/type/Xamarin.Forms.Picker/ 实际上它是RadionButton Xamarin.forms

的最佳替代方案

答案 10 :(得分:0)

XLabs RadioButton和BindableRadioGroup运作良好:XLabs RadioButton for Xamarin Forms

这是使用BindableRadioGroup的简单是/否广播:

var answers = new List<string>();
answers.Add("Yes");
answers.Add("No");

var RadioGroup = new XLabs.Forms.Controls.BindableRadioGroup()
{
  ItemsSource = answers, 
  Orientation = StackOrientation.Horizontal
};

答案 11 :(得分:0)

Xamarin Forms现在提供了一个单选按钮控件。

在此处查看文档:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/radiobutton

从XF 4.8开始,这仍处于试验阶段,我尚未使用此功能,因此无法评论其稳定性。