RelativeSource in MAUI control not bound - xaml

I'm going through simple example explained in video:
https://youtu.be/5Qga2pniN78?t=961
At 16. minute (timestamp in link above), he implements the Delete Command on SwipeItem.
In my local project, everything worked so far, but Delete Command is never triggered. I checked source generators, DeleteCommand exists.
My XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage"
xmlns:viewmodel="clr-namespace:MauiApp1.ViewModel"
x:DataType="viewmodel:MainViewModel">
<Grid RowDefinitions="100, Auto, *"
ColumnDefinitions=".75*, .25*"
Padding="10"
RowSpacing="10"
ColumnSpacing="10">
<Image Grid.ColumnSpan="2" Source="tom.jpg"
BackgroundColor="Transparent"></Image>
<Entry Placeholder="Enter task" Grid.Row="1" Text="{Binding Text}"></Entry>
<Button Text="Add" Grid.Row="1" Grid.Column="1" Command="{Binding AddCommand}"></Button>
<CollectionView Grid.Row="2" Grid.ColumnSpan="2" ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="{x:Type x:String}">
<SwipeView>
<SwipeView.RightItems>
<SwipeItem Text="Delete" BackgroundColor="Red"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=DeleteCommand}"
CommandParameter="{Binding .}">
</SwipeItem>
</SwipeView.RightItems>
<Grid Padding="0,5">
<Frame>
<Label Text="{Binding .}" FontSize="24"></Label>
</Frame>
</Grid>
</SwipeView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</ContentPage>
View Model:
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace MauiApp1.ViewModel
{
public partial class MainViewModel : ObservableObject
{
public MainViewModel()
{
Items = new();
Items.Add("test");
}
[ObservableProperty]
private ObservableCollection<string> items;
[ObservableProperty]
private string text;
[RelayCommand]
private void Add()
{
if (string.IsNullOrWhiteSpace(text))
{
return;
}
Items.Add(Text);
Text = string.Empty;
}
[RelayCommand]
private void Delete(string s)
{
if (Items.Contains(s))
{
Items.Remove(s);
}
}
}
}
Why is DeleteCommand not triggering?

try this
Command="{Binding BindingContext.DeleteCommand,
Source={x:Reference myPage}}"
where myPage is your page's name
<ContentPage x:Name="myPage" ...

Resolved,
I forgot to add <SwipeItems> element after <SwipeView.RightItems>.

AncestorType={x:Type viewmodel:MainViewModel}
Your viewmodel is not part of the visual tree, so you can't bind to it with relative source anyway.
You can use your CollectionView's Binding Context and then the specific property you need:
Command="{Binding BindingContext.DeleteCommand, Source={RelativeSource AncestorType={x:Type CollectionView}}}

Related

What is the correct way to use RelativeSource in the outer tag?

I want to avoid repeating Source={RelativeSource AncestorType={x:Type vm:MainViewModel}} in the following.
<SwipeView ... xmlns:vm="clr-namespace:Todo.ViewModel">
<SwipeView.LeftItems>
<SwipeItems>
<SwipeItem Text="Delete"
Command="{Binding DeleteCommand,Source={RelativeSource AncestorType={x:Type vm:MainViewModel}}}" />
</SwipeItems>
</SwipeView.LeftItems>
<Grid Padding="0,5">
<Frame >
<Frame.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding TapCommand,Source={RelativeSource AncestorType={x:Type vm:MainViewModel}}}"/>
</Frame.GestureRecognizers>
</Frame>
</Grid>
</SwipeView>
I do the following but it does not work as expected.
<SwipeView ... xmlns:vm="clr-namespace:Todo.ViewModel"
BindingContext="{Binding Source={RelativeSource AncestorType={x:Type vm:MainViewModel}}}"
>
<SwipeView.LeftItems>
<SwipeItems>
<SwipeItem Text="Delete" Command="{Binding DeleteCommand}" />
</SwipeItems>
</SwipeView.LeftItems>
<Grid Padding="0,5">
<Frame >
<Frame.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TapCommand}" />
</Frame.GestureRecognizers>
</Frame>
</Grid>
</SwipeView>
Repo
Use the following repo to avoid getting inconsistent results (among us) and to make sure we are talking in the same scope.
https://github.com/pstricks-fans/Todo
Here are the relevant parts:
MySwipeView:
public partial class MySwipeView : SwipeView
{
public MySwipeView()
{
InitializeComponent();
}
}
<SwipeView ...
x:Class="Todo.CustomControls.MySwipeView"
xmlns:vm="clr-namespace:Todo.ViewModel"
>
<SwipeView.LeftItems>
<SwipeItems>
<SwipeItem
Text="Delete"
Command="{Binding DeleteCommand,Source={RelativeSource AncestorType={x:Type vm:MainViewModel}}}"
CommandParameter="{Binding .}"/>
</SwipeItems>
</SwipeView.LeftItems>
<Grid Padding="0,5">
<Frame >
<Frame.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding TapCommand,Source={RelativeSource AncestorType={x:Type vm:MainViewModel}}}"
CommandParameter="{Binding .}"/>
</Frame.GestureRecognizers>
<Label Text="{Binding .}" FontSize="24"/>
</Frame>
</Grid>
</SwipeView>
MainPage:
public partial class MainPage : ContentPage
{
public MainPage(MainViewModel vm)
{
InitializeComponent();
BindingContext = vm;
}
}
<ContentPage ...
xmlns:local="clr-namespace:Todo.CustomControls"
xmlns:vm="using:Todo.ViewModel"
x:DataType="vm:MainViewModel"
>
<Grid ... >
<CollectionView ... >
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="{x:Type x:String}">
<local:MySwipeView />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</ContentPage>
MainViewModel:
public partial class MainViewModel : ObservableObject
{
[RelayCommand]
void Delete(string s){}
[RelayCommand]
async Task Tap(string s){}
}
In your case, SwipeView is being used inside an ItemTemplate. You MUST NOT change its BindingContext; that has to be the associated Item.
Therefore, your original goal is NOT POSSIBLE; we can simplify the "Source" expression, but we cannot eliminate it.
Simplest I know is:
Command="{Binding VM.DeleteCommand, Source={x:Reference thePage}}"
Explanation: On "thePage", finds property "VM", which contains a property "DeleteCommand". Make the following changes to MainPage.
<ContentPage
...
x:Name="thePage"
x:Class="MainPage">
class MainPage : ContentPage
{
// You can change this name. Be sure to use same name in XAML above.
public property MainViewModel VM { get; set; }
public MainPage(MainViewModel vm)
{
InitializeComponent();
// Put this line BEFORE set BindingContext. Used by XAML.
VM = vm;
BindingContext = vm;
}
At first, the format of binding to an ancestor in the official document is something like {Binding Source={RelativeSource AncestorType={x:Type local:PeopleViewModel}}, Path=DeleteEmployeeCommand}
And then you can try to set the SwipeView's binding context in the construction method instead of the binding way you used.
I have done a sample to test, and the binding worked well:
The MySwipeView.cs :
public partial class MySwipeView : SwipeView
{
      public ICommand TestCommand { get; private set; }
      public MySwipeView()
      {
            InitializeComponent();
            TestCommand = new Command<string>(Test);
//BindingContext = this;
            BindingContext = new MyViewModel();
      }
      void Test(string print)
      {
            Debug.WriteLine("============"+print);
      }
}
The MySwipeView.xaml:
<SwipeView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiAppTest.MySwipeView"
>
<SwipeView.LeftItems>
<SwipeItems>
<SwipeItem
Text="Delete"
Command="{Binding DeleteCommand}"
CommandParameter="xxxxxxxxx"/>
</SwipeItems>
</SwipeView.LeftItems>
<Grid Padding="0,5">
<Frame >
<Frame.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding TapCommand}"
CommandParameter="xxxxxxxx"/>
</Frame.GestureRecognizers>
<Label Text="xxxxxxxx" FontSize="24"/>
</Frame>
</Grid>
</SwipeView>
The MainPage.xaml:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MauiApp21"
x:Class="MauiApp21.MainPage">
<HorizontalStackLayout>
<local:MySwipeView/>
</HorizontalStackLayout>
</ContentPage>
The MyViewModel.cs:
public partial class MyViewModel : ObservableObject
{
[RelayCommand]
void Delete(string value) { Debug.WriteLine("===========Delete"); }
[RelayCommand]
void Tap(string value) { Debug.WriteLine("===============Tap"); }
}
No matter the BindingContext is this or the MyViewModel, the command will run successfully.

Stumped on Xamarin databinding cast exception

I've followed examples and worked with XAML for WPF and this never happens so I'm totally confused about why Xamarin Forms is complaining.
Here's a simple form where I'm trying to use a ListView. The general structure is what was generated by Visual Studio but I've put in the ListView with an template for drawing two Labels:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="PrivateDiary.Views.AboutPage"
xmlns:vm="clr-namespace:PrivateDiary.ViewModels"
Title="{Binding Title}">
<ContentPage.BindingContext>
<vm:AboutViewModel />
</ContentPage.BindingContext>
<ContentPage.Resources>
<ResourceDictionary>
<Color x:Key="Accent">#96d1ff</Color>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout Orientation="Vertical">
<ListView x:Name="AboutListView"
ItemsSource="{Binding Items}"
SelectionMode="None">
<ListView.ItemTemplate>
<DataTemplate>
<Grid VerticalOptions="Center" HorizontalOptions="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" Grid.Column="0" />
<Label Text="{Binding Detail}" Grid.Column="1" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
The code behind:
namespace PrivateDiary.Views
{
using Xamarin.Forms;
public partial class AboutPage : ContentPage
{
public AboutPage()
{
InitializeComponent();
}
}
}
and my View Model:
namespace PrivateDiary.ViewModels
{
using System.Collections.ObjectModel;
public class AboutViewModel : BaseViewModel
{
public ObservableCollection<AboutItem> Items { get; set; } = new ObservableCollection<AboutItem>();
public AboutViewModel()
{
Title = "About";
Items.Add(new AboutItem {Name = "Version", Detail = "0.3"});
Items.Add(new AboutItem {Name = "Privacy Policy", Detail = "#privacy"});
}
}
public class AboutItem
{
public string Name { get; set; }
public string Detail { get; set; }
}
}
BaseViewModel is the stock one generated by Visual Studio 2019 (16.10.3) so I won't list it here. It implements the details for INotifyPropertyChanged, a page Title property and IsBusy property.
When I run the app I get this:
If I removed the Items.Add(...) lines there's no problems.
Any ideas why it fails to cast?
Please add element ViewCell outside of element Grid in your xaml
You can refer to the following code:
<ContentPage.BindingContext>
<listviewapp1:AboutViewModel></listviewapp1:AboutViewModel>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout Orientation="Vertical">
<ListView x:Name="AboutListView"
ItemsSource="{Binding Items}"
SelectionMode="None">
<ListView.ItemTemplate>
<DataTemplate>
<!--add ViewCell here-->
<ViewCell>
<Grid VerticalOptions="Center" HorizontalOptions="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" Grid.Column="0" />
<Label Text="{Binding Detail}" Grid.Column="1" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>

How bind a command in DataTemplate in Resource Dictionary?

I'm trying to make a better solution architecture, for that I've separated many parts of code in differents files. Because my application use a lot of DataTemplates, I push them in different ResourceDictionary.xaml files.
Problem :
I have a view Agenda.xaml, with the viewModel AgendaViewModel. This view have a ListView which call's datatemplate in external ResourceDictionary file. But if I want put a Binding Command in the dataTemplate, the command is never executed because (I guess) the resource Dictionary where is my DataTemplate not reference ViewModel.
What can I do ?
I've already tried some weird Binding code like
<TapGestureRecognizer Command="{Binding BindingContext.OpenActiviteCommand, Source={x:Reference agendaPage}}" CommandParameter="{Binding .}"/>
Where "agendaPage" is the x:Name of Agenda.xaml.
All I found on Google was about WPF and Binding property not available on Xamarin Forms (RelativeSource, ElementName etc...)
I know I can put dataTemplate in my Agenda.xaml view, but I really want keep it in an external file. I want avoid view files with 1500 lines....
This is my Agenda.xaml view
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Corim.Portable.CorimTouch.ViewForms.Agenda.AgendaViewDetail"
xmlns:converters="clr-namespace:Corim.Portable.CorimTouch.Converters"
Title="Agenda"
x:Name="agendaPage">
<ContentPage.Content>
<Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="{StaticResource LightGrayCorim}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Liste itv,pointage,activite -->
<ListView
x:Name="listAgenda"
Grid.Row="1"
SeparatorVisibility="None"
HasUnevenRows="True"
SelectionMode="None"
CachingStrategy="RecycleElement"
ItemsSource="{Binding AgendaList}"
ItemTemplate="{StaticResource agendaTemplateSelector}"
BackgroundColor="{StaticResource LightGrayCorim}">
</ListView>
</Grid>
</ContentPage.Content>
</ContentPage>
And this is one part of Datatemplate in AgendaTemplates.xaml
<DataTemplate x:Key="agenda-adresse-intervention">
<ViewCell>
<Frame Margin="10,5,10,0" HasShadow="False" Padding="0" CornerRadius="10" IsClippedToBounds="True">
<controls:CustomTappedStackLayout
BackgroundColor="White"
TappedBackgroundColor="{StaticResource RollOver}"
HorizontalOptions="FillAndExpand"
Orientation="Horizontal"
Padding="10">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding Path=BindingContext.OpenParcCommand, Source={x:Reference agendaPage}}" CommandParameter="{Binding .}" NumberOfTapsRequired="1"/>
</StackLayout.GestureRecognizers>
<Image
Source="localisation_adresse"
WidthRequest="30"
HeightRequest="30"
Aspect="AspectFit"
HorizontalOptions="Start"
Margin="10"
VerticalOptions="StartAndExpand"/>
<StackLayout
HorizontalOptions="FillAndExpand"
Orientation="Vertical">
<Label
Text="{Binding Client}"
IsVisible="{Binding Client, Converter={StaticResource StringEmptyBooleanConverter}}"
FontFamily="{StaticResource SemiBoldFont}"
FontSize="{StaticResource MediumTextSize}"
TextColor="Black"/>
<Label
Text="{Binding Title}"
IsVisible="{Binding Title, Converter={StaticResource StringEmptyBooleanConverter}}"
FontFamily="{StaticResource RegularFont}"
FontSize="{StaticResource DefaultTextSize}"
TextColor="Gray"/>
</StackLayout>
</controls:CustomTappedStackLayout>
</Frame>
</ViewCell>
</DataTemplate>
But if I want put a Binding Command in the dataTemplate, the command
is never executed because (I guess) the resource Dictionary where is
my DataTemplate not reference ViewModel.
You guess wrong: it's totally fine to do what you are doing and should work transparently. The binding is resolved at runtime your data template does not know anything about the object that will be bound.
1st: drop the BindingContext.OpenActiviteCommand nonsense :) Just bind to OpenActiviteCommand, the only question is:
2nd: Where is your OpenActiviteCommand ?
The data context of your AgendaTemplates is the item in your AgendaList.
If the type of the AgendaList is an ObservableCollection<AgendaViewModel>, and your AgendaViewModel has a OpenParcCommand then it should be fine:
public class AgendaViewModel
{
public AgendaViewModel(ICommand openParcCommand)
{
OpenParcCommand = openParcCommand;
}
public ICommand OpenParcCommand { get; }
}
and in your AgendaPageViewModel:
public class AgendaPageViewModel
{
public ObservableCollection<AgendaViewModel> AgendaList { get; }
}
Thanks to #Roubachof
The soluce was replace my ListView of InterventionModel by ListView of AgendaDataViewModel.
AgendaViewModel is a new class which contains all the commands I need, and an InterventionModel.
this is AgendaDataViewModel :
public class AgendaDataViewModel : HybridContentViewModel
{
private InterventionModel _model;
public InterventionModel Model
{
get => _model;
set { _model = value; }
}
public ICommand OpenActiviteCommand { get; private set; }
public AgendaDataViewModel()
{
this.OpenActiviteCommand = new Command<InterventionModel>(this.OpenActivite);
}
/// <summary>
/// Ouvre le formulaire d'édition de l'activité
/// </summary>
/// <param name="model"></param>
private void OpenActivite(InterventionModel model)
{
//TODO amener sur le formulaire d'activité
}
}
my AgendaTemplate.xaml
<!--Template pour l'affichage du parc-->
<DataTemplate x:Key="agenda-adresse-intervention">
<ViewCell>
<Frame Margin="10,5,10,0" HasShadow="False" Padding="0" CornerRadius="10" IsClippedToBounds="True">
<controls:CustomTappedStackLayout
BackgroundColor="White"
TappedBackgroundColor="{StaticResource RollOver}"
HorizontalOptions="FillAndExpand"
Orientation="Horizontal"
Padding="10">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding OpenParcCommand}" CommandParameter="{Binding Model}" NumberOfTapsRequired="1"/>
</StackLayout.GestureRecognizers>
<Image
Source="localisation_adresse"
WidthRequest="30"
HeightRequest="30"
Aspect="AspectFit"
HorizontalOptions="Start"
Margin="10"
VerticalOptions="StartAndExpand"/>
<StackLayout
HorizontalOptions="FillAndExpand"
Orientation="Vertical">
<Label
Text="{Binding Model.Client}"
IsVisible="{Binding Model.Client, Converter={StaticResource StringEmptyBooleanConverter}}"
FontFamily="{StaticResource SemiBoldFont}"
FontSize="{StaticResource MediumTextSize}"
TextColor="Black"/>
<Label
Text="{Binding Model.Title}"
IsVisible="{Binding Model.Title, Converter={StaticResource StringEmptyBooleanConverter}}"
FontFamily="{StaticResource RegularFont}"
FontSize="{StaticResource DefaultTextSize}"
TextColor="Gray"/>
</StackLayout>
</controls:CustomTappedStackLayout>
</Frame>
</ViewCell>
</DataTemplate>
As you can see, the values binding is made by this line :
{Binding Model.Client}
where Client is the name of Binded property. And to Bind a Command, you don't need Model, and just bind like this :
Command={Binding CommandName}
Hope it helps someone in the future !

How can i capture the event of a tapped item (located in a template) from the base class?

I have a base grid
<Grid Grid.Row="1" Grid.Column="1" x:Name="GridName">
<StackLayout Orientation="Vertical">
<art:GridOptionsView ItemsSource="{Binding Items}" >
<art:GridOptionsView.ItemTemplate>
<DataTemplate>
<uikit:DashboardItemTemplate />
</DataTemplate>
</art:GridOptionsView.ItemTemplate>
</art:GridOptionsView>
</StackLayout>
</Grid>
which uses the following DashboardItemTemplate
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
BackgroundColor="White">
<ContentView.Content>
<Grid Padding="0">
<StackLayout VerticalOptions="Center" HorizontalOptions="Center" Orientation="Vertical" Spacing="10">
<Grid>
<Label Text="" Style="{StaticResource FontIcon}" HorizontalTextAlignment="Center" Opacity="1" FontSize="130" TextColor="{Binding BackgroundColor}" VerticalOptions="Center" HorizontalOptions="Center" IsVisible="{Binding Source={x:Reference Root}, Path=ShowiconColoredCircleBackground}" />
<Label Text="{Binding Icon}" Style="{StaticResource FontIcon}" Opacity="1" TextColor="White" VerticalOptions="Center" HorizontalOptions="Center" />
</Grid>
<Label Text="{Binding Name}" TextColor="{Binding Source={x:Reference Root}, Path=TextColor}" FontSize="14" HorizontalTextAlignment="Center">
</Label>
</StackLayout>
</Grid>
</ContentView.Content>
<ContentView.GestureRecognizers>
<TapGestureRecognizer Tapped="OnWidgetTapped" />
</ContentView.GestureRecognizers>
</ContentView>
How can i capture the "OnWidgetTapped" event on my base xaml class?
I do this usually with a custom bindable property ParentBindingContext in my template:
public class MyTemplate : ContentPage
{
public static BindableProperty ParentBindingContextProperty = BindableProperty.Create(nameof(ParentBindingContext),
typeof(object), typeof(BasePageTemplate));
public object ParentBindingContext
{
get { return GetValue(ParentBindingContextProperty); }
set { SetValue(ParentBindingContextProperty, value); }
}
}
And then in your page (which contains the template) just set the ParentBindingContext:
<DataTemplate>
<template:MyTemplate ParentBindingContext="{Binding BindingContext, Source={x:Reference Name=MyPageName}}" />
</DataTemplate>
With that you can access the full BindingContext of your page in your template. The following example of a command shows how the template can bind to a command MyCommand, which is in the BindingContext of the page:
Command="{Binding ParentBindingContext.MyCommand, Source={x:Reference Name=MyTemplatePageName}}"
But this presupposes that your page has a BindingContext behind (like a ViewModel). This ViewModel then contains the "global" commands for the whole page. These commands (or just methods) can then be accessed by the template, because they know about the BindingContext of the page.
I changed an answer from flow description to the code. The idea is to create ItemTemplate programatically and pass to its constructor the page with list (or grid). Define a function ItemTemplateTapped and call it from template.
EventOnGridPage
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ButtonRendererDemo.EventOnGridPage">
<ListView x:Name="listView" >
</ListView>
</ContentPage>
EventOnGridPage code behind
public partial class EventOnGridPage : ContentPage
{
public EventOnGridPage()
{
InitializeComponent();
listView.ItemsSource = new List<Contact>
{
new Contact { Name = "Kirti",Status = "True"},
new Contact { Name = "Nilesh",Status = "False"}
};
listView.ItemTemplate = new DataTemplate(loadTemplate);
}
private object loadTemplate()
{
return new ViewCell() { View = new EventOnGridTemplate(this) };
}
public void ItemTemplateTapped(string name)
{
DisplayAlert("ItemTemplateTapped", name, "OK");
}
}
EventOnGridTemplate xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ButtonRendererDemo.EventOnGridTemplate"
BackgroundColor="Green">
<Label Text="{Binding Name}" x:Name="myLabel"></Label>
</ContentView>
EventOnGridTemplate code behind
public partial class EventOnGridTemplate
{
EventOnGridPage parent;
public EventOnGridTemplate(EventOnGridPage parent)
{
this.parent = parent;
InitializeComponent();
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += TapGestureRecognizer_Tapped;
myLabel.GestureRecognizers.Add(tapGestureRecognizer);
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
parent.ItemTemplateTapped(myLabel.Text);
}
}
If you already defined the tap gesture binding in the XAML code, you don't need to add the TapGestureRecognizer, simply sign your method to an event listener method:
Your XAML:
<ContentView.GestureRecognizers>
<TapGestureRecognizer Tapped="OnWidgetTapped" />
</ContentView.GestureRecognizers>
On C# code behind:
public void OnWidgetTapped(object sender, EventArgs args)
{
// do stuff here
}
You just need to implement your OnWidgetTapped method:
void OnWidgetTapped(object sender, System.EventArgs e)
{
// Do stuff here
}
Another solution. If you implemented OnWidgetTapped as was suggested you can use sender.Parent.Parent... till you get to the object you want - grid or page. Cast it to for example EventOnGridPage and then call the function of that object.

Xamarin.Forms: How to diplay a modal when an item in ListView is clicked?

Good Day everyone. I'm currently doing a simple application in Xamarin.Forms that allows me to CRUD record of an Employee. The created records are displayed on a ListView. Here's my screenshot.
What I want to do is whenever I click an Item on the ListView, is it will display a modal with a more detailed information of an Employee e.g (Birthday, Address, Gender, Work Experience). How can I do that? Is that even possible? Can you show me how?
This is my code that displays the ListView.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinFormsDemo.EmployeeRecordsPage"
xmlns:ViewModels="clr-namespace:XamarinFormsDemo.ViewModels;assembly=XamarinFormsDemo"
xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions"
BackgroundImage="bg3.jpg"
Title="List of Employees">
<ContentPage.BindingContext>
<ViewModels:MainViewModel/>
</ContentPage.BindingContext>
<StackLayout Orientation="Vertical">
<ListView ItemsSource="{Binding EmployeesList, Mode=TwoWay}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10" RowSpacing="10" ColumnSpacing="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<controls:CircleImage Source="icon.png"
HeightRequest="66"
HorizontalOptions="CenterAndExpand"
Aspect="AspectFill"
WidthRequest="66"
Grid.RowSpan="2"
/>
<Label Grid.Column="1"
Text="{Binding Name}"
TextColor="#24e97d"
FontSize="24"/>
<Label Grid.Column="1"
Grid.Row="1"
Text="{Binding Department}"
TextColor="White"
FontSize="18"
Opacity="0.6"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackLayout Orientation="Vertical"
Padding="30,10,30,10"
HeightRequest="20"
BackgroundColor="#24e97d"
VerticalOptions="Center"
Opacity="0.5">
<Label Text="© Copyright 2015 smesoft.com.ph All Rights Reserved "
HorizontalTextAlignment="Center"
VerticalOptions="Center"
HorizontalOptions="Center" />
</StackLayout>
</StackLayout>
</ContentPage>
NOTE: Records that are displayed are CREATED in ASP.NET Web Application and just displayed on a ListView in UWP. If you need to see more codes, just please let me know.
Thanks a lot Guys.
To bind a command to item selected property see the example bellow otherwise ItemSelected will bind to a model property only
For full example see https://github.com/TheRealAdamKemp/Xamarin.Forms-Tests/blob/master/RssTest/View/Pages/MainPage.xaml.cs
Now you can bind an Icommand which could have something like
private Command login;
public ICommand Login
{
get
{
login = login ?? new Command(DoLogin);
return login;
}
}
private async void DoLogin()
{
await Navigation.PopModalAsync(new MySampXamlPage());
//await DisplayAlert("Hai", "thats r8", "ok");
}
and view :
[Navigation.RegisterViewModel(typeof(RssTest.ViewModel.Pages.MainPageViewModel))]
public partial class MainPage : ContentPage
{
public const string ItemSelectedCommandPropertyName = "ItemSelectedCommand";
public static BindableProperty ItemSelectedCommandProperty = BindableProperty.Create(
propertyName: "ItemSelectedCommand",
returnType: typeof(ICommand),
declaringType: typeof(MainPage),
defaultValue: null);
public ICommand ItemSelectedCommand
{
get { return (ICommand)GetValue(ItemSelectedCommandProperty); }
set { SetValue(ItemSelectedCommandProperty, value); }
}
public MainPage ()
{
InitializeComponent();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
RemoveBinding(ItemSelectedCommandProperty);
SetBinding(ItemSelectedCommandProperty, new Binding(ItemSelectedCommandPropertyName));
}
protected override void OnAppearing()
{
base.OnAppearing();
_listView.SelectedItem = null;
}
private void HandleItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
{
return;
}
var command = ItemSelectedCommand;
if (command != null && command.CanExecute(e.SelectedItem))
{
command.Execute(e.SelectedItem);
}
}
}
XAML:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:ValueConverters="clr-namespace:RssTest.ValueConverters;assembly=RssTest"
x:Class="RssTest.View.Pages.MainPage"
Title="{Binding Title}">
<ContentPage.Resources>
<ResourceDictionary>
<ValueConverters:BooleanNegationConverter x:Key="not" />
</ResourceDictionary>
</ContentPage.Resources>
<Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<ListView x:Name="_listView"
IsVisible="{Binding IsLoading, Converter={StaticResource not}" ItemsSource="{Binding Items}"
ItemSelected="HandleItemSelected"
VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Title}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<ActivityIndicator IsVisible="{Binding IsLoading}" IsRunning="{Binding IsLoading}"
VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
</Grid>
</ContentPage>