2015-06-11 17 views
6

Sono completamente nuovo per xamarin.forms, ho bisogno di aggiungere una casella di controllo, i pulsanti di opzione e l'elenco a discesa. Ho provato alcuni campioni dalla rete ma non riesco a ottenere la casella di controllo. Qualcuno può aiutarmi a raggiungere questo in xamarin.forms?Come aggiungere Checkbox in Xamarin.Forms nel file Xaml?

file XAML

<toolkit:CheckBox Text ="Employee" 
        FontSize="20" 
        CheckedChanged ="OnClicked"/> 

o

<controls:CheckBox DefaultText="Default text" 
           HorizontalOptions="FillAndExpand" 
           TextColor="Green" 
           FontSize="25" 
           FontName="AmericanTypewriter"/> 

Alcuni link o codice di esempio renderà più facile da capire.

risposta

-2

Non c'è CheckBox, ma è possibile utilizzare un Switch:

<Switch android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 

Solo nel caso in cui si desidera valori diversi, è possibile specificarli così:

<Switch android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:checked="true" 
     android:textOn="YES" 
     android:textOff="NO" /> 
+2

Non è xamarin.form, si campiona in realtà Xamarin.Android! –

2

è necessario aggiungere Nuget pacchetto chiamato Xlabs.form. Prova a importare nel file XAML cs come:

using Xlabs.Forms.Controls; 

Se il tentativo di aggiungere nel file cs basta aggiungere la linea come:

CheckBox chk=new CheckBox() 
      { 
       checked=false; 
      }; 

In AXML è diverso:

<CheckBox x:Name="checked" isSelected="{Binding flag}"/> 

Oppure è possibile utilizzare <controls:checkbox>.

Nota: Non dimenticare di aggiungere la riga in basso nella Contentpage di Xaml:

xmlns:controls="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms" 
+1

I moduli XLabs hanno notificato sulla loro pagina Github che il codice non viene mantenuto. Può o non può supportare la versione aggiornata di Xamarin Forms. – luckyShubhra

+0

Grazie per l'informazione. Molti dei nostri progetti utilizzano Xlabs per la casella di controllo. Se si dispone di un altro supporto plu-in da Nuget Package, è necessario cercarlo .. –

+0

Con l'aiuto di aboves di @Sawan e utilizzando le ans accettate dal forum Xamarin ho creato una mia casella di controllo personalizzata. È possibile collegare [qui] (https://forums.xamarin.com/discussion/70704/checkbox-with-xamarin). – luckyShubhra

1

ho implementato la casella di controllo e discesa nel file .cs di Xamarin platform.I incrociati suggerisco di usare i file cs per la creazione della UI.Xamarin fornisce la leva per utilizzare uno delle funzionalità sia file o AXML cs per creare l'interfaccia utente

using System; 
using Xamarin.Forms; 
using XLabs.Forms.Controls; 

namespace Facedetection 
{ 
    public class firstPage : ContentPage 
    { 
     string statename; 

     public firstPage() 
     { 

      CheckBox checkbox = new CheckBox() { 
       TextColor=Color.Blue, 
       CheckedText="I am checked" 

      }; 

      Picker statepick = new Picker(); 
      statepick.WidthRequest = 300; 
      statepick.Title = "Select a state"; 
      statepick.Items.Add ("India"); 
      statepick.Items.Add ("US"); 
      statepick.Items.Add ("Arizona"); 
      statepick.Items.Add ("China"); 

      statepick.SelectedIndexChanged += (sender, e) => { 
       if (statepick.SelectedIndex == -1) { 
        DisplayAlert ("Title", "Item not selected", "ok"); 
       } else { 
        statename = statepick.Items [statepick.SelectedIndex]; 
        Console.WriteLine ("Selected country is:" + statename); 
       } 
      }; 




      Content = new StackLayout { 
       Children = { 
        checkbox,statepick 
       } 
      }; 
     } 
    } 
} 




worked for me 
+0

Questo non risponde alla domanda che era come aggiungerlo in un file Xaml. Ty però per il contributo! – Kasper

8

ho trovato un modo migliore per fare questo che è quello di creare il proprio. Era davvero piuttosto semplice. Creare un file cs in un progetto Risorse (o dove mai volete) chiamato CheckBox e incolla questo codice:

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

} 
} 

C'è probabilmente un modo migliore per fare questo, ma ho solo aggiunto le due immagini nelle posizioni appropriate in ogni progetto (base per UWP, Risorse/Disegnabile per Android).

enter image description here

Quindi per utilizzare nel vostro Xaml basta fare una cosa del genere (io ho usato un convertitore bc ero vincolanti per un valore stringa):

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

Nota: È necessario impostare l'BindingContext nelle tue pagine cs file per il controllo di lavorare. Quindi il tuo codice di codice delle pagine dietro dovrebbe assomigliare a questo:

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

      this.BindingContext = MyBindingObject; 
     } 
    } 
} 

E questo è il risultato!

enter image description here

Spero che questo aiuti qualcuno !!

UPDATE:

Il seguente è il nuovo codice che rimuove lo sfondo grigio su disabili e permette anche il testo per avvolgere se non si adatta allo schermo. Questo utilizza un ContentView che contiene una griglia che può espandersi in base al contenuto.

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

} 
+0

Ciao Kasper, grazie per le grandi cose. Ho provato il codice aggiornato, ma sto ancora ottenendo un bordo delineato alle mie caselle di controllo. Per favore fatemi sapere come posso rimuovere quel confine. Anche nel mio caso non ho bisogno di alcun testo contro la casella di controllo. –

+0

Ciao Ravindra. Ho aggiornato nuovamente il codice per rimuovere il bordo quando si passa il mouse. Il bordo era dal pulsante che stavo usando. Ho rimosso il pulsante e ho utilizzato un riconoscitore di gesti. Tuttavia, se tutto ciò di cui hai bisogno è un quadrato spuntato o non controllato, il mio esempio è eccessivo. Il tuo esempio sarebbe molto più efficiente. =) – Kasper

+0

Perfetto !!! Grazie Kasper. –

1

In base a Kasper Answers, ma utilizzando l'immagine anziché un pulsante in modo che non mostri l'ombra.

public class CustomCheckbox : Image 
{ 
    private const string CheckboxUnCheckedImage = "checkbox_unchecked"; 
    private const string CheckboxCheckedImage = "checkbox_checked"; 

    public CustomCheckbox() 
    { 
     Source = CheckboxUnCheckedImage; 
     var imageTapGesture = new TapGestureRecognizer(); 
     imageTapGesture.Tapped += ImageTapGestureOnTapped; 
     GestureRecognizers.Add(imageTapGesture); 
     PropertyChanged += OnPropertyChanged; 
    } 

    private void ImageTapGestureOnTapped(object sender, EventArgs eventArgs) 
    { 
     if (IsEnabled) 
     { 
      Checked = !Checked; 
     } 
    } 

    /// <summary> 
    /// The checked changed event. 
    /// </summary> 
    public event EventHandler<bool> CheckedChanged; 

    /// <summary> 
    /// The checked state property. 
    /// </summary> 
    public static readonly BindableProperty CheckedProperty = BindableProperty.Create("Checked", typeof(bool), typeof(CustomCheckbox), false, BindingMode.TwoWay, propertyChanged: OnCheckedPropertyChanged); 

    public bool Checked 
    { 
     get 
     { 
      return (bool)GetValue(CheckedProperty); 
     } 

     set 
     { 
      if (Checked != value) 
      { 
       SetValue(CheckedProperty, value); 
       CheckedChanged?.Invoke(this, value); 
      } 
     } 
    } 

    private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) 
    { 
     if (e?.PropertyName == IsEnabledProperty.PropertyName) 
     { 
      Opacity = IsEnabled ? 1 : 0.5; 
     } 
    } 

    private static void OnCheckedPropertyChanged(BindableObject bindable, object oldValue, object newValue) 
    { 
     var checkBox = bindable as CustomCheckbox; 
     if (checkBox != null) 
     { 
      var value = newValue as bool?; 
      checkBox.Checked = value.GetValueOrDefault(); 
      checkBox.Source = value.GetValueOrDefault() ? CheckboxCheckedImage : CheckboxUnCheckedImage; 
     } 
    } 
} 
+0

Ciò non consente un datacontext o di impostare il testo su un'associazione. Ho aggiornato il mio codice originale per rimuovere lo sfondo grigio e anche per consentire il text wrapping se il testo della casella di controllo non si adatta allo schermo. – Kasper

Problemi correlati