如何在Xaml文件中的Xamarin.Forms中添加Checkbox?

Man*_*noj 10 c# checkbox xaml xamarin.ios

我是xamarin.forms的新手,我需要添加一个复选框,单选按钮和下拉列表.我从网上尝试了一些样本,但我无法获得复选框.任何人都可以帮助我在xamarin.forms中实现这一目标吗?

Xaml文件

<toolkit:CheckBox Text ="Employee"
                  FontSize="20"
                  CheckedChanged ="OnClicked"/>
Run Code Online (Sandbox Code Playgroud)

要么

<controls:CheckBox DefaultText="Default text"
                               HorizontalOptions="FillAndExpand"
                               TextColor="Green"
                               FontSize="25"
                               FontName="AmericanTypewriter"/>
Run Code Online (Sandbox Code Playgroud)

一些链接或示例代码将使其更容易理解.

Kas*_*per 19

我发现了一种更好的方法来创建自己的方法.这真的很简单.在一个名为CheckBox的Resources项目(或任何你想要的地方)创建一个cs文件并粘贴这段代码:

namespace Resources.Controls
{

public class Checkbox : Button 
{
    public Checkbox()
    {
        base.Image = "Image_Unchecked.png";
        base.Clicked += new EventHandler(OnClicked);
        base.SizeChanged += new EventHandler(OnSizeChanged);
        base.BackgroundColor = Color.Transparent;
        base.BorderWidth = 0;
    }

    private void OnSizeChanged(object sender, EventArgs e)
    {
        //if (base.Height > 0)
        //{
        //    base.WidthRequest = base.Height;
        //}
    }

    public static BindableProperty CheckedProperty = BindableProperty.Create(
        propertyName: "Checked",
        returnType: typeof(Boolean?),
        declaringType: typeof(Checkbox),
        defaultValue: null,
        defaultBindingMode: BindingMode.TwoWay,
        propertyChanged: CheckedValueChanged);

    public Boolean? Checked
    {
        get
        {
            if (GetValue(CheckedProperty) == null)
            {
                return null;
            }
            return (Boolean)GetValue(CheckedProperty);
        }
        set
        {
            SetValue(CheckedProperty, value);
            OnPropertyChanged();
            RaiseCheckedChanged();
        }
    }

    private static void CheckedValueChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (newValue != null && (Boolean)newValue == true)
        {
            ((Checkbox)bindable).Image = "Image_Checked.png";
        }
        else
        {
            ((Checkbox)bindable).Image = "Image_Unchecked.png";
        }
    }

    public event EventHandler CheckedChanged;
    private void RaiseCheckedChanged()
    {
        if (CheckedChanged != null)
            CheckedChanged(this, EventArgs.Empty);
    }

    private Boolean _IsEnabled = true;
    public Boolean IsEnabled
    {
        get
        {
            return _IsEnabled;
        }
        set
        {
            _IsEnabled = value;
            OnPropertyChanged();
            if (value == true)
            {
                this.Opacity = 1;
            }
            else
            {
                this.Opacity = .5;
            }
            base.IsEnabled = value;
        }
    }

    public void OnEnabled_Changed()
    {

    }

    public void OnClicked(object sender, EventArgs e)
    {
        Checked = !Checked;

        // Call the base class event invocation method.
        //base.Clicked(sender, e);
    }

}
}
Run Code Online (Sandbox Code Playgroud)

可能有更好的方法,但我只是将两个图像添加到每个项目中的适当位置(UWP的基础,Android的Resources/Drawable).

在此输入图像描述

然后在你的Xaml中使用它只是做这样的事情(我使用转换器bc我绑定到字符串值):

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:controls="clr-namespace:Resources.Controls;assembly=Resources"
             x:Class="MyNameSpace.CheckBoxExamplePage"
             Title=" Hygiene">
  <Grid Padding="1">
    <ScrollView Padding="4">
      <StackLayout>
        <StackLayout Orientation="Horizontal">
          <controls:Checkbox x:Name="cbHello" Text="Hello CheckBox" Checked="{Binding Path=My.Binding.Path, Converter={StaticResource StringToBoolean}, Mode=TwoWay}" />
        </StackLayout>
        <StackLayout Orientation="Horizontal" Padding="16,0,0,0">
          <controls:Checkbox x:Name="cbDisabled" Text="Disabled Example" IsEnabled="False" Checked="{Binding Path=My.Binding.PathTwo, Converter={StaticResource StringToBoolean}, Mode=TwoWay}" />
        </StackLayout>
      </StackLayout>
    </ScrollView>
  </Grid>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)

注意:您必须在页面cs文件中设置BindingContext才能使检查生效.因此,您的页面代码隐藏文件应如下所示:

namespace MyNameSpace
{
    public partial class CheckBoxExamplePage
    {
        public CheckBoxExamplePage(object MyBindingObject)
        {
            InitializeComponent();

            this.BindingContext = MyBindingObject;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是结果!

在此输入图像描述

希望这有助于某人!

更新:

以下是删除禁用时灰色背景的新代码,如果文本不适合屏幕,也允许文本换行.这使用包含可以根据内容进行扩展的网格的ContentView.

    public class Checkbox : ContentView
{
    protected Grid ContentGrid;
    protected ContentView ContentContainer;
    public Label TextContainer;
    protected Image ImageContainer;

    public Checkbox()
    {
        var TapGesture = new TapGestureRecognizer();
        TapGesture.Tapped += TapGestureOnTapped;
        GestureRecognizers.Add(TapGesture);

        ContentGrid = new Grid
        {
            VerticalOptions = LayoutOptions.FillAndExpand,
            HorizontalOptions = LayoutOptions.FillAndExpand
        };

        ContentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(42) });
        ContentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        ContentGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });

        ImageContainer = new Image
        {
            VerticalOptions = LayoutOptions.Center,
            HorizontalOptions = LayoutOptions.Center,
        };
        ImageContainer.HeightRequest = 42;
        ImageContainer.WidthRequest = 42;

        ContentGrid.Children.Add(ImageContainer);

        ContentContainer = new ContentView
        {
            VerticalOptions = LayoutOptions.FillAndExpand,
            HorizontalOptions = LayoutOptions.FillAndExpand,
        };
        Grid.SetColumn(ContentContainer, 1);

        TextContainer = new Label
        {
            TextColor = Color.White,
            VerticalOptions = LayoutOptions.Center,
            HorizontalOptions = LayoutOptions.FillAndExpand,
        };
        ContentContainer.Content = TextContainer;

        ContentGrid.Children.Add(ContentContainer);

        base.Content = ContentGrid;

        this.Image.Source = "Image_Unchecked.png";
        this.BackgroundColor = Color.Transparent;
    }

    public static BindableProperty CheckedProperty = BindableProperty.Create(
        propertyName: "Checked",
        returnType: typeof(Boolean?),
        declaringType: typeof(Checkbox),
        defaultValue: null,
        defaultBindingMode: BindingMode.TwoWay,
        propertyChanged: CheckedValueChanged);

    public static BindableProperty TextProperty = BindableProperty.Create(
        propertyName: "Text",
        returnType: typeof(String),
        declaringType: typeof(Checkbox),
        defaultValue: null,
        defaultBindingMode: BindingMode.TwoWay,
        propertyChanged: TextValueChanged);

    public Boolean? Checked
    {
        get
        {
            if (GetValue(CheckedProperty) == null)
                return null;
            return (Boolean)GetValue(CheckedProperty);
        }
        set
        {
            SetValue(CheckedProperty, value);
            OnPropertyChanged();
            RaiseCheckedChanged();
        }
    }

    private static void CheckedValueChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (newValue != null && (Boolean)newValue == true)
            ((Checkbox)bindable).Image.Source = "Image_Checked.png";
        else
            ((Checkbox)bindable).Image.Source = "Image_Unchecked.png";
    }

    public event EventHandler CheckedChanged;
    private void RaiseCheckedChanged()
    {
        if (CheckedChanged != null)
            CheckedChanged(this, EventArgs.Empty);
    }

    private Boolean _IsEnabled = true;
    public Boolean IsEnabled
    {
        get { return _IsEnabled; }
        set
        {
            _IsEnabled = value;
            OnPropertyChanged();
            this.Opacity = value ? 1 : .5;
            base.IsEnabled = value;
        }
    }

    public event EventHandler Clicked;
    private void TapGestureOnTapped(object sender, EventArgs eventArgs)
    {
        if (IsEnabled)
        {
            Checked = !Checked;
            if (Clicked != null)
                Clicked(this, new EventArgs());
        }
    }

    private static void TextValueChanged(BindableObject bindable, object oldValue, object newValue)
    {
        ((Checkbox)bindable).TextContainer.Text = (String)newValue;
    }

    public event EventHandler TextChanged;
    private void RaiseTextChanged()
    {
        if (TextChanged != null)
            TextChanged(this, EventArgs.Empty);
    }

    public Image Image
    {
        get { return ImageContainer; }
        set { ImageContainer = value; }
    }

    public String Text
    {
        get { return (String)GetValue(TextProperty); }
        set
        {
            SetValue(TextProperty, value);
            OnPropertyChanged();
            RaiseTextChanged();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)


Vik*_*m B 1

您需要添加名为 Xlabs.form 的 Nuget 包。尝试将其导入到您的 Xaml.cs 文件中,例如:

using XLabs.Forms.Controls;
Run Code Online (Sandbox Code Playgroud)

此外,您还必须在 .cs 文件中添加以下行:

CheckBox chk=new CheckBox()
            {
                checked=false;
            };
Run Code Online (Sandbox Code Playgroud)

在 Xaml 中则有所不同:

<CheckBox  x:Name="checked" isSelected="{Binding flag}"/>
Run Code Online (Sandbox Code Playgroud)

或者你可以使用<controls:checkbox>.

注意:不要忘记在 Xaml 的内容页中添加以下行:

 xmlns:controls="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms"
Run Code Online (Sandbox Code Playgroud)

  • XLabs Forms 已在其 Github 页面上通知代码未得到维护。它可能支持也可能不支持 Xamarin Forms 的更新版本。 (5认同)