1800 pág.

Pré-visualização | Página 27 de 50
usuário no modo de exibição. No entanto, às vezes, a exibição precisa conter botões que acionam várias ações no ViewModel. Mas o ViewModel não deve conter Clicked manipuladores para os botões porque que seria empate ViewModel de um paradigma de interface de usuário específica. Para permitir que ViewModels seja mais independente de objetos de interface de usuário específico, mas ainda permitir a ser chamado dentro de ViewModel métodos um comando interface existe. Os seguintes elementos no xamarin. Forms dá suporte para essa interface de comando: Button MenuItem ToolbarItem SearchBar TextCell (e, portanto, também ImageCell ) ListView TapGestureRecognizer Com exceção do SearchBar e ListView elemento, esses elementos definem duas propriedades: Command do tipo System.Windows.Input.ICommand CommandParameter do tipo Object O SearchBar define SearchCommand e SearchCommandParameter propriedades, enquanto o ListView define uma RefreshCommand propriedade do tipo ICommand . O ICommand interface define dois métodos e um evento: void Execute(object arg) bool CanExecute(object arg) using System; using System.ComponentModel; using System.Windows.Input; using Xamarin.Forms; namespace XamlSamples { class KeypadViewModel : INotifyPropertyChanged { string inputString = ""; string displayText = ""; char[] specialChars = { '*', '#' }; public event PropertyChangedEventHandler PropertyChanged; // Constructor public KeypadViewModel() { AddCharCommand = new Command<string>((key) => { // Add the key to the input string. InputString += key; }); DeleteCharCommand = new Command(() => { // Strip a character from the input string. InputString = InputString.Substring(0, InputString.Length - 1); }, () => { // Return true if there's something to delete. return InputString.Length > 0; }); } // Public properties public string InputString { protected set { event EventHandler CanExecuteChanged O ViewModel pode definir as propriedades do tipo ICommand . Em seguida, você pode vincular essas propriedades para o Command propriedade de cada Button ou outro elemento, ou talvez uma exibição personalizada que implementa essa interface. Você pode definir opcionalmente o CommandParameter propriedade para identificar individuais Button objetos (ou outros elementos) que estão associados a essa propriedade ViewModel. Internamente, o Button chamadas a Execute método sempre que o usuário toca o Button , passando para o Execute método seu CommandParameter . O CanExecute método e CanExecuteChanged são usados para casos onde um Button toque pode ser válido no momento, caso em que o Button deve desabilitar a mesmo. O Button chamadas CanExecute quando o Command propriedade é definida pela primeira vez e sempre que o CanExecuteChanged evento é acionado. Se CanExecute retorna false , o Button desabilita a mesmo e não gera Execute chamadas. Para obter ajuda sobre como adicionar comandos à sua ViewModels, xamarin. Forms define duas classes que implementam ICommand : Command e Command<T> onde T é o tipo dos argumentos para Execute e CanExecute . Essas duas classes definem vários construtores mais um ChangeCanExecute método ViewModel pode chamar para forçar o Command objeto acionar o CanExecuteChanged evento. Aqui está um ViewModel para um teclado simple que é destinado para inserir números de telefone. Observe que o Execute e CanExecute método são definidas como diretamente de funções de lambda no construtor : { if (inputString != value) { inputString = value; OnPropertyChanged("InputString"); DisplayText = FormatText(inputString); // Perhaps the delete button must be enabled/disabled. ((Command)DeleteCharCommand).ChangeCanExecute(); } } get { return inputString; } } public string DisplayText { protected set { if (displayText != value) { displayText = value; OnPropertyChanged("DisplayText"); } } get { return displayText; } } // ICommand implementations public ICommand AddCharCommand { protected set; get; } public ICommand DeleteCharCommand { protected set; get; } string FormatText(string str) { bool hasNonNumbers = str.IndexOfAny(specialChars) != -1; string formatted = str; if (hasNonNumbers || str.Length < 4 || str.Length > 10) { } else if (str.Length < 8) { formatted = String.Format("{0}-{1}", str.Substring(0, 3), str.Substring(3)); } else { formatted = String.Format("({0}) {1}-{2}", str.Substring(0, 3), str.Substring(3, 3), str.Substring(6)); } return formatted; } protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } Esse ViewModel supõe que o AddCharCommand propriedade está vinculada a Command propriedade de vários botões (ou qualquer outra coisa que tenha uma interface de comando), cada um deles é identificada pelo CommandParameter . Esses botões adicionam caracteres para um InputString propriedade, que é formatada <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:XamlSamples;assembly=XamlSamples" x:Class="XamlSamples.KeypadPage" Title="Keypad Page"> <Grid HorizontalOptions="Center" VerticalOptions="Center"> <Grid.BindingContext> <local:KeypadViewModel /> </Grid.BindingContext> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="80" /> <ColumnDefinition Width="80" /> <ColumnDefinition Width="80" /> </Grid.ColumnDefinitions> <!-- Internal Grid for top row of items --> <Grid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Frame Grid.Column="0" OutlineColor="Accent"> <Label Text="{Binding DisplayText}" /> </Frame> <Button Text="⇦" Command="{Binding DeleteCharCommand}" Grid.Column="1" BorderWidth="0" /> </Grid> <Button Text="1" Command="{Binding AddCharCommand}" CommandParameter="1" Grid.Row="1"