Xamarin Forms - Binding a function to StackLayout TapGesture - xamarin

In my view I have:
<ContentView.BindingContext>
<vm:HomeViewModel />
</ContentView.BindingContext>
In that viewmodel I have:
public void test(object sender, EventArgs e)
{
var x = 0;
}
That's just for testing so I can hit a breakpoint, but I can't seem to Bind the function to the View:
<StackLayout BackgroundColor="White">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding test }" />
</StackLayout.GestureRecognizers>
I've tried to hook it up with Tapped property as well, adding parentheses, I keep getting:
Severity Code Description Project File Line Suppression State
Error Position 57:51. No method OnTapGestureRecognizerTapped with correct signature found on type
I know I'm missing something here, can anyone shed some light on my problem?

You need a command in your viewmodel binding to:
public ICommand cmdTest { get { return new Command(() => test())
Now in your view you are able to bind to cmdTest:
<TapGestureRecognizer Command="{Binding cmdTest}" />

Related

Xamarin Forms: System.ObjectDisposedException when setting Focus to an Entry control

I have the following Xamarin Forms page that throws an exception on this line...
The first time this page is loaded, the OnAppearing works fine, sets the focus properly, and doesn't throw an exception.
When I navigate back to this page (ie, logout), OnAppearing is throwing the following...
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Xamarin.Forms.Platform.Android.EntryRenderer'.
What is the best way to set focus to a control on a page in Xamarin Forms?
I'm not sure what is in your XAML, but if you define the x:Name="_entry" on the Entry in XAML, and use that name to access the control directly instead of FindByName, it should work fine.
I try to reproduce your issue at my side, but it works fine and there is no issue when I click Button to navigate another page and coming back. Please take a look my code:
<StackLayout>
<Label
HorizontalOptions="CenterAndExpand"
Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand" />
<Entry
x:Name="UserNameentry"
HorizontalOptions="FillAndExpand"
VerticalOptions="CenterAndExpand" />
<Button
x:Name="btn1"
Clicked="btn1_Clicked"
HeightRequest="50"
HorizontalOptions="FillAndExpand"
Text="btn1"
VerticalOptions="CenterAndExpand"
WidthRequest="200" />
</StackLayout>
public Page4()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
var usernameentry = FindByName("UserNameentry") as Entry;
usernameentry.Focus();
}
private async void btn1_Clicked(object sender, EventArgs e)
{
Page3 page = new Page3();
await Navigation.PushModalAsync(page);
}
If you still have this issue, please provide some code about xaml here.

How can I make the Tapped event of a ViewCell send a param to a generic function and then open up a picker for that ViewCell element?

Update: Just a reminder, there's a 500 point bonus on this if someone can just show me how to implement this functionality without using Gestures>
I am using a ViewCell and a gesture recognizer to open up a picker with the following code. The ViewCell has a label on the left and a label area on the right that is populated initially when the app starts and later with the picker when the ViewCell is clicked.
XAML
<ViewCell x:Name="ati" Tapped="OpenPickerCommand">
<Grid VerticalOptions="CenterAndExpand" Padding="20, 0">
<Grid.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding OpenPickerCommand}"
CommandParameter="{x:Reference atiPicker}" NumberOfTapsRequired="1" />
</Grid.GestureRecognizers>
<local:LabelBodyRendererClass Text="Answer Time Interval" HorizontalOptions="StartAndExpand" />
<Picker x:Name="atiPicker" IsVisible="false" HorizontalOptions="End" SelectedIndexChanged="atiPickerSelectedIndexChanged" ItemsSource="{Binding Times}"></Picker>
<local:LabelBodyRendererClass x:Name="atiLabel" HorizontalOptions="End"/>
</Grid>
</ViewCell>
<ViewCell x:Name="pti" Tapped="OpenPickerCommand">
<Grid VerticalOptions="CenterAndExpand" Padding="20, 0">
<Grid.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding OpenPickerCommand}"
CommandParameter="{x:Reference ptiPicker}" NumberOfTapsRequired="1" />
</Grid.GestureRecognizers>
<local:LabelBodyRendererClass Text="Phrase Time Interval" HorizontalOptions="StartAndExpand" />
<Picker x:Name="ptiPicker" IsVisible="false" HorizontalOptions="End" SelectedIndexChanged="ptiPickerSelectedIndexChanged" ItemsSource="{Binding Times}"></Picker>
<local:LabelBodyRendererClass x:Name="ptiLabel" HorizontalOptions="End"/>
</Grid>
</ViewCell>
C# This works for different pickers (ati, bti, pti etc) with CommandParameter
public SettingsPage()
{
InitializeComponent();
BindingContext = new CommandViewModel();
}
void atiPickerSelectedIndexChanged(object sender, EventArgs e)
{
var picker = (Picker)sender;
int selectedIndex = picker.SelectedIndex;
if (selectedIndex != -1)
{
App.DB.UpdateIntSetting(Settings.Ati, selectedIndex);
atiLabel.Text = AS.ati.Text();
}
}
void ptiPickerSelectedIndexChanged(object sender, EventArgs e)
{
var picker = (Picker)sender;
int selectedIndex = picker.SelectedIndex;
if (selectedIndex != -1)
{
App.DB.UpdateIntSetting(Settings.Pti, selectedIndex);
ptiLabel.Text = AS.pti.Text();
}
}
public class CommandViewModel: ObservableProperty
{
public ICommand openPickerCommand;
public CommandViewModel()
{
openPickerCommand = new Command<Picker>(PickerFocus);
//openPickerCommand = new Command(tapped);
}
public ICommand OpenPickerCommand
{
get { return openPickerCommand; }
}
void PickerFocus(Picker param)
{
param.Focus();
}
}
I would like to remove the use of TapGestureRecognizers but I still want to retain the functionality and layout.
It's been suggested to me that it would be better if I used the Tapped event of the ViewCell like this:
Tapped="OnTapped"
Can someone explain in some detail how I could wire this up in C#. Would I be best to code something into the CommandViewModel as well as in the C# backing code. Also can the view model have one method that takes an argument so it could be used to open up different pickers?
An example of how I could do this would be very much appreciated. Note that I don't particularly need to use the CommandViewModel if there is a way that I could do this by coding just in the .cs backing code.
(Sorry for the poor english)
Despite not being best practice, I guess you can do something like this, dismissing the viewmodel:
XAML:
<ViewCell x:Name="ati" Tapped="OpenPickerCommand">
<Grid VerticalOptions="CenterAndExpand" Padding="20, 0">
<local:LabelBodyRendererClass Text="Answer Time Interval" HorizontalOptions="StartAndExpand" />
<Picker x:Name="atiPicker"
IsVisible="false"
HorizontalOptions="End"
SelectedIndexChanged="atiPickerSelectedIndexChanged"
ItemsSource="{Binding Times}">
</Picker>
<local:LabelBodyRendererClass x:Name="atiLabel" HorizontalOptions="End"/>
</Grid>
</ViewCell>
<ViewCell x:Name="pti" Tapped="OpenPickerCommand">
<Grid VerticalOptions="CenterAndExpand" Padding="20, 0">
<local:LabelBodyRendererClass Text="Phrase Time Interval" HorizontalOptions="StartAndExpand" />
<Picker x:Name="ptiPicker" IsVisible="false" HorizontalOptions="End" SelectedIndexChanged="ptiPickerSelectedIndexChanged" ItemsSource="{Binding Times}"></Picker>
<local:LabelBodyRendererClass x:Name="ptiLabel" HorizontalOptions="End"/>
</Grid>
</ViewCell>
C#:
private void OpenPickerCommand(object sender, System.EventArgs e)
{
if (sender != null)
{
Picker pkr = sender == ati ? atiPicker : ptiPicker;
pkr.Focus();
}
}
Answering your question "Can the view model have one method that takes an argument?", it is exactly what you're already doing using the 'OpenPickerCommand' method. The problem is that using the ViewCell's public event 'Tapped', you can't set parameters to the delegate handler.
Let me know if it works for you or if you do need some more information.
I hope it helps.
You can solve this with attached properties. Simply define a "behavior" class for ViewCell that adds the Command/Parameter properties.
public static class TappedCommandViewCell
{
private const string TappedCommand = "TappedCommand";
private const string TappedCommandParameter = "TappedCommandParameter";
public static readonly BindableProperty TappedCommandProperty =
BindableProperty.CreateAttached(
TappedCommand,
typeof(ICommand),
typeof(TappedCommandViewCell),
default(ICommand),
BindingMode.OneWay,
null,
PropertyChanged);
public static readonly BindableProperty TappedCommandParameterProperty =
BindableProperty.CreateAttached(
TappedCommandParameter,
typeof(object),
typeof(TappedCommandViewCell),
default(object),
BindingMode.OneWay,
null);
private static void PropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if (bindable is ViewCell cell)
{
cell.Tapped -= ViewCellOnTapped;
cell.Tapped += ViewCellOnTapped;
}
}
private static void ViewCellOnTapped(object sender, EventArgs e)
{
if (sender is ViewCell cell && cell.IsEnabled)
{
var command = GetTappedCommand(cell);
var parameter = GetTappedCommandParameter(cell);
if (command != null && command.CanExecute(parameter))
{
command.Execute(parameter);
}
}
}
public static ICommand GetTappedCommand(BindableObject bindableObject) =>
(ICommand)bindableObject.GetValue(TappedCommandProperty);
public static void SetTappedCommand(BindableObject bindableObject, object value) =>
bindableObject.SetValue(TappedCommandProperty, value);
public static object GetTappedCommandParameter(BindableObject bindableObject) =>
bindableObject.GetValue(TappedCommandParameterProperty);
public static void SetTappedCommandParameter(BindableObject bindableObject, object value) =>
bindableObject.SetValue(TappedCommandParameterProperty, value);
}
After that reference your behavior namespace in XAML and specify the property values using fully qualified names:
<ViewCell StyleId="disclosure-indicator"
behaviors:TappedCommandViewCell.TappedCommand="{Binding BrowseCommand}"
behaviors:TappedCommandViewCell.TappedCommandParameter="https://www.google.com">
<StackLayout Orientation="Horizontal">
<Label Text="Recipient"
VerticalOptions="Center"
Margin="20,0"/>
<Label Text="{Binding LedgerRecord.Recipient}"
HorizontalOptions="EndAndExpand"
VerticalOptions="Center"
Margin="0,0,20,0"/>
</Label>
</StackLayout>
</ViewCell>
The above will allow you to use MVVM and no Tap Gesture Recognizers.
The first problem is that you're mixing the code-behind and MVVM
approaches in the same code. It is confusing and certainly not the
right way to code what you want to achieve. So, all commanding must
be in the ViewModel attached to the View, no code-behind apart some
code only used for UI effects.
There is no need to define a gesture recognizer for all visual items since you just want to detect the tap on all the surface of the viewcell. To achieve this you must define all children of the ViewCell with InputTransparent=true. So the tap will not be detected and will be trapped by the parent ViewCell (you
must indicate the InpuTransparent because there is no tap event
bubbling in X.Forms).
Showing and Hidding the picker is a View problem not a ViewModel one. So here you can use some code-behind to create an event handler for the ViewCell Tapped event. This handler will just set visible=true on the picker.
The picker selected event must be connected to a corresponding Command in the ViewModel. So each time the picker is displayed and a value is selected your viewmodel will be aware of the action. This is the only command you need in your viewmodel. Depending of XForms version the picker has no bindable command, so you can use one of the numerous "bindablepicker" implementation you can find on the web or you can also use a XAML EventToCommand Behavior.
So there is two different problems : showing/hidding the picker which can be achieved directly in XAML or with the help of a bit of code-behind; and the picker item selection that must be managed using a Command in the viewmodel.
Hoping this will help you

How to pass parameter to command

I have Xamarin Forms solution and on one page there is list with images. When image is clicked, I would like to trigger procedure witch has image path as parameter. In xaml I define image with:
<Image Source="{Binding ImagePath}"
WidthRequest="30" HeightRequest="30"
HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" >
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TapImageCommand}" CommandParameter="{Binding ImagePath}" />
</Image.GestureRecognizers>
</Image>
and TapImageCommand is defined in view model's constructor as:
TapImageCommand = new Command<string>(ImagePath =>
{
OnImageTapped(ImagePath);
});
and TapImageCommand is defined with:
public ICommand TapImageCommand { get; set; }
Problem is OnImageTapped is never triggered. What am I doing wrong?
The problem here is that you think you are binding the ImagePath of the object behind the list, but you are not. Look at the Command you are binding, this is part of the PageModel, not the object in the list, so neither is the CommandParameter.
Therefore, ImagePath is probably null, and it does not match the signature you have for the Command which expects a string.
In this particular case it is probably easiest to supply the whole object as a parameter and get out the property yourself. I will assume the object in the list is of type Foo, then edit your code like underneath.
In your view, edit the TapGestureRecognizer to this:
TapGestureRecognizer Command="{Binding TapImageCommand}" CommandParameter="{Binding .}" />
The dot points to itself, in this case the specific instance of Foo in your list. Then edit the Command like this:
TapImageCommand = new Command<Foo>(fooObject =>
{
OnImageTapped(fooObject);
});
Now in your OnImageTapped method you can extract the ImagePath property.
In my case I was looking for selected Index of stack layout or grid and it was done as below.
Command Added as below
public ICommand SelectedItem
{
get
{
return new Command<string>((x) => OpenChild(x));
}
}
public void OpenChild(string x)
{
//handle parameter x to say "Hello " + x
}
Added command on XAML
SelectionChangedCommand="{Binding SelectedItem}" SelectionChangedCommandParameter="{Binding SelectedItem, Source={RelativeSource Self}}

Xamarin.Forms - Prism EventToCommandBehavior passing an object to a new view is converted to a string

I've been trying the Prism framework for Xamarin.Forms lately and I've encountered an issue with EventToCommandBehavior which I am quite sure of it should work.
When I am trying to send an object from a ListView to a new view with NavigationParameters() it is automatically generated to a string instead of the object that was sent before.
As I try to cast it to an object an InvalidCastException shows up.
ListView.cs where I send the data from to a new view via Navigate():
private ObservableCollection<Employee> _employeeList = new ObservableCollection<Employee>();
_employeeList.Add("employee", new Employee{ Id = 1, FirstName = "FirstTest", LastName = "LastTest" });
private async void Navigate()
{
var employeePara = new NavigationParameters();
employeePara.Add("employee", _selectedEmployee);
await _navigationService.NavigateAsync("EmployeeDetail" + employeePara);
}
New view, where I try to get the data as an object:
private Employee _employee;
public void OnNavigatingTo(NavigationParameters parameters)
{
try
{
if (parameters.ContainsKey("employee"))
_employee = (Employee)parameters["employee"]; // invalid cast happening here
EmployeeFullName = _employee.FirstName;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
XAML:
<ContentPage.Resources>
<ResourceDictionary>
<c:ItemTappedEventArgsConverter x:Key="itemTappedEventArgs" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<ListView ItemsSource="{Binding EmployeeList}" SelectedItem="{Binding SelectedEmployee}">
<ListView.Behaviors>
<b:EventToCommandBehavior
EventName="ItemTapped"
Command="{Binding EmployeeTappedCommand}"/>
</ListView.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding FullName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
The Prism for Forms example also uses a similar scenario, but has a different NavigateAsync method signature.
My guess, yours is wrong?
Example code await _navigationService.NavigateAsync("RecipePage", p);
Example solution https://github.com/PrismLibrary/Prism-Samples-Forms/blob/master/ContosoCookbook/ContosoCookbook/ContosoCookbook/ViewModels/MainPageViewModel.cs#L35

How can I remove item form ListView in Xamarin Cross Platform Forms MVVM

How can I remove item form ListView in Xamarin Cross Platform Forms
<ViewCell.ContextActions>
<MenuItem Text="Delete" IsDestructive="True" Command="Binding DleteItemCommand}" />
</ViewCell.ContextActions>
But I want user code complies with MVVM pattern.
So, View model is just for presentation layer, you need interact with your cell instead of viewmodel. Follow the next steps:
1.Create a Observable collection of ViewModels for Cells.
2. Add this collection to ItemSource of ListView.
3. Then for command add callback method
<ListView x:Name="citiesListView" ItemTapped="OnSelection">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="DeleteAction" Text="Delete" IsDestructive="true" CommandParameter="{Binding .}" />
</ViewCell.ContextActions>
<StackLayout Padding="15,0">
<Label
Text="{Binding .}"
FontSize="30"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
Then in code:
public partial class YourPage : ContentPage
{
public ObservableCollection<string> YourCollection { get; set; }
public YourPage()
{
InitializeComponent();
// initialize at this point
YourCollection = new ObservaleCollection(<Some collection of view models>);
citiesListView.ItemsSource = YourCollection;
}
private void DeleteAction(object sender, System.EventArgs e)
{
var menuItem = ((MenuItem)sender);
var yourViewModel = (YourViewModelType) menuItem.CommandParameter;
YourCollection.Remove(yourViewModel);
}
You can add ObservableCollection<YourType> and in command delete element from collection.
var collection = new ObservableCollection<YourType>();
yourList.ItemSource = collection;
// in Command
public void OnDelete (object sender, EventArgs e)
{
// getting reference on menu item
var menuItem = ((MenuItem)sender).CommandParameter;
// cast to underlying viewModel
var yourObject = (YourType)menuItem;
collection.Remove(yourObject);
}
Yes, it is compatible with MVVM pattern. So, you have a Cell in ListView and it is a single representation of viewModel. And using it is approach you have the next relationship: "model - viewModel - view". ObservableCollection has a references on ViewModels that you display in ListView's Cells, and you now can easily delete cells that you want. See improvements above in code

Resources