How to filter in Xamarin - xamarin

I am quite new to Xamarin and I want to make filtering in xamarin. So I have three buttons drinks, food and all. When it is all I want to show all of them and when the drinks button is clicked I only want to show drinks etc.
So here are my buttons:
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
<Button Text="All" x:Name="All" Clicked="Handle_Filter" TextColor="#EEF2FF" FontSize="18" HorizontalOptions="Center" BackgroundColor="#FF5959" />
</StackLayout>
<StackLayout Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center">
<Button Text="Food" x:Name="Food" Clicked="Handle_Filter" TextColor="#676FA3" FontSize="18" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
</StackLayout>
<StackLayout Grid.Column="2" HorizontalOptions="Center" VerticalOptions="Center">
<Button Text="Drinks" x:Name="Drinks" Clicked="Handle_Filter" TextColor="#676FA3" FontSize="18" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
</StackLayout>
And the area which needs to be filtered:
<CollectionView Grid.Row="3" Margin="25" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
SelectionMode="None" ItemsSource="{Binding AllProducts}">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical" ItemSpacing="20"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<pv:PancakeView HasShadow="True" BackgroundColor="#EEF2FF" VerticalOptions="StartAndExpand"
HorizontalOptions="FillAndExpand">
<Grid ColumnSpacing="3" HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<BoxView Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
<BoxView Grid.Column="1" Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
<BoxView Grid.Column="2" Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
<Button
Text="{Binding Name}"
Grid.Column="0"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"
BackgroundColor="#EEF2FF"
/>
</Grid>
</pv:PancakeView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
And my products:
public class Product
{
public string Type { get; set; }
public string Name { get; set; }
public int Stock { get; set; }
}
And help would be appreciated since I am really new in Xamarin.
Thanks

you can do this with a LINQ query
protected void FilterFood(object sender, EventArgs args)
{
myCollectionView.ItemsSource = AllProducts.Where(x => x.Type == "Food").ToList();
}

Your Buttons in Xaml file:
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
<Button Text="All" x:Name="All" Clicked="onAllFilterClicked" TextColor="#EEF2FF" FontSize="18" HorizontalOptions="Center" BackgroundColor="#FF5959" />
</StackLayout>
<StackLayout Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center">
<Button Text="Food" x:Name="Food" Clicked="onFoodFilterClicked" TextColor="#676FA3" FontSize="18" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
</StackLayout>
<StackLayout Grid.Column="2" HorizontalOptions="Center" VerticalOptions="Center">
<Button Text="Drinks" x:Name="Drinks" Clicked="onDrinksFilterClicked" TextColor="#676FA3" FontSize="18" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
</StackLayout>
Set a name to your CollectionView x:Name="cvProducts"
On your Buttons .cs file:
protected void onAllFilterClicked(object sender, EventArgs args)
{
cvProducts.ItemsSource = AllProducts;
}
protected void onFoodFilterClicked(object sender, EventArgs args)
{
cvProducts.ItemsSource = AllProducts.Select(x => x.Type == "Food").ToList();
}
protected void onDrinksFilterClicked(object sender, EventArgs args)
{
cvProducts.ItemsSource = AllProducts.Select(x => x.Type == "Drinks").ToList();
}

Related

Changing BackgroundColor of Button within Xamarin CollectionView changes the BackgroundColor of every 8th button down. why?

I have a Xamarin CollectionView That uses a Button (Button x:Name="PNameButton") to Change the Background color of the button.
When the Button is clicked the background color changes... However - So does every 8th Button in the CollectionView. Its as if the CollectionView renders new data every 8 or so items, and that new first button gets the changed color property. How do I fix this? Code Follows:
<CollectionView x:Name="PairingsCollectionView" SelectionMode="Multiple" Margin="20,5,20,5" >
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Margin="0" Padding="0,0,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="35" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<BoxView Grid.Column="0" Grid.Row="0" Margin="0" Color="#333130"/>
<Button x:Name="PNameButton" Margin="0" Padding="0,0,0,0" Grid.Column="0" BackgroundColor="{Binding UseColor}" Text="{Binding PDisplayName}" FontSize="Small" TextColor="Black"
HorizontalOptions="Start" VerticalOptions="Center" Clicked="Button_Clicked" />
<BoxView Grid.Column="1" Grid.Row="0" Color="#333130" Margin="0"></BoxView>
<Label Margin="0" Padding="0,0,0,0" Grid.Column="1" TextColor="White" FontSize="Small"
HorizontalOptions="Center" VerticalOptions="Center" >
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding PDays, StringFormat='{0}Dy'}"/>
<Span Text=" "/>
<Span Text="{Binding PDay}"/>
</FormattedString>
</Label.FormattedText>
</Label>
<BoxView Grid.Row="0" Grid.Column="2" Margin="0" Color="#333130"></BoxView>
<Label Margin="0" Padding="0,0,0,0" Grid.Column="2" Text="{Binding PCredit, StringFormat='{0}'}" TextColor="#F57BFA" FontSize="Small"
HorizontalOptions="Center" VerticalOptions="Center"/>
<BoxView Grid.Row="0" Grid.Column="3" Color="#333130" Margin="0"></BoxView>
<Label Margin="0" Padding="0,0,0,0" Grid.Column="3" Text="{Binding PFlightTime, StringFormat='{0}'}" TextColor="White" FontSize="Small"
HorizontalOptions="Center" VerticalOptions="Center"/>
<BoxView Grid.Row="0" Grid.Column="4" Color="#333130" Margin="0"/>
<Label Margin="0" Padding="0,0,0,0" Grid.Column="4" Text="{Binding PRegionType, StringFormat='{0}'}" TextColor="White" FontSize="Small" HorizontalOptions="Center" VerticalOptions="Center"/>
<BoxView Grid.Row="0" Grid.Column="5" Color="#333130" Margin="0"/>
<CheckBox x:Name="IsSelectedCheckbox" Grid.Row="0" Grid.Column="5" IsChecked="{Binding PIsSelected}" VerticalOptions="Center"/>
<BoxView Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1" Color="LightGray"></BoxView>
<Label Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1" Text="{Binding PDateModified}" TextColor="Black" FontSize="Small"
HorizontalOptions="Center" VerticalOptions="Center"/>
<BoxView Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="5" Color="LightGray" ></BoxView>
<Label Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="5" Text="{Binding PLayovers}"
TextColor="Coral" FontAttributes="Bold" FontSize="17" HorizontalOptions="Start" VerticalOptions="Center" Margin="5,0,0,0" />
<WebView Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="6" BackgroundColor="#333130"
MinimumHeightRequest="150" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
HeightRequest="{Binding PWebViewHeight}" >
<WebView.Source>
<HtmlWebViewSource Html="{Binding PAllText}"/>
</WebView.Source>
</WebView>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
And in the Code Behind:
private void Button_Clicked(object sender, EventArgs e)
{
try
{
string ChkVal = "";
bool compareBool = false;
bool currentState = false;
Color buttonColer;
string ColorHexVal;
int i = 0;
var thisButton = sender as Button;
buttonColer = thisButton.BackgroundColor;
ColorHexVal = buttonColer.ToHex();
if (buttonColer != Color.FromHex("#F7F75A"))
{
currentState = true;
}
else
{
currentState = false;
}
var PairingItem = ((Button)sender).Parent.BindingContext as Pairings;
compareBool = App.DatabaseNA.GetIsSelected(PairingItem.PID);
if (!compareBool == true)
{
thisButton.BackgroundColor = Color.FromHex("#46AE3C");
}
else
{
thisButton.BackgroundColor = Color.FromHex("#F7F75A");
}
}
catch (Exception ex)
{
DisplayAlert("Alert", ex.InnerException.ToString(), "OK"); //await
}
}
Again - Thank You!!!
The code works great and sets the Background color of the button... The problem is - It sets the Background Color of every Button about 8 items down.
Thanks

Xamarin.forms - Gridview row height error

My ContentPage have a Grid inside a ListView that contains a column (x:Name="stlNomeMiniatura") with a label and an image, as below:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="InventarioBensCelular.MainPage"
BackgroundColor="White">
<ContentPage.Content>
<StackLayout>
<StackLayout Orientation="Vertical" VerticalOptions="Start" HeightRequest="130" Background="#003399">
<StackLayout Orientation="Horizontal" HorizontalOptions="Start" VerticalOptions="Start" HeightRequest="40" Margin="7,10">
<StackLayout Orientation="Horizontal">
<Image Source="Icone.png" Aspect="Fill" HeightRequest="40" WidthRequest="48" VerticalOptions="Center"
HorizontalOptions="Start"/>
</StackLayout>
<StackLayout Orientation="Horizontal" WidthRequest="300" HeightRequest="40">
<StackLayout Orientation="Vertical">
<Label x:Name="lblTitulo" Text="Inventário de Bens" FontSize="17" FontAttributes="Bold"
VerticalOptions="Start" TextColor="White" Padding="0,-2,0,0"/>
<Label x:Name="lblSubtitulo" Text="Transmissão de Foto" FontSize="17" FontAttributes="Bold"
VerticalOptions="Start" TextColor="White" Padding="0,-7,0,0"/>
</StackLayout>
</StackLayout>
<StackLayout Orientation="Horizontal" HorizontalOptions="EndAndExpand" VerticalOptions="Center" HeightRequest="40">
<ImageButton Source="ParametrosVerde.png" HorizontalOptions="Center" VerticalOptions="Center"
HeightRequest="32" WidthRequest="32" Clicked="Parametro_Clicou"/>
</StackLayout>
</StackLayout>
<StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand" VerticalOptions="Start">
<StackLayout WidthRequest="160" Margin="7,0">
<Frame x:Name="TiraFoto" CornerRadius="10" BorderColor="DarkGreen" HorizontalOptions="StartAndExpand"
Padding="0" HeightRequest="32" VerticalOptions="Start" BackgroundColor="#E0FFE0" WidthRequest="160">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="TiraFoto_Clicou" />
</Frame.GestureRecognizers>
<StackLayout Orientation="Horizontal" HorizontalOptions="StartAndExpand" Padding="10,0,0,0">
<Image Source="Camera.png" Aspect="Fill" HeightRequest="26" WidthRequest="24" VerticalOptions="Center" HorizontalOptions="Start"/>
<Label Text="Tirar Uma Foto" FontSize="16" FontAttributes="Bold" VerticalTextAlignment="Center" HorizontalOptions="Start"
TextColor="DarkGreen"/>
</StackLayout>
</Frame>
</StackLayout>
<StackLayout WidthRequest="160">
<Frame x:Name="Sair" CornerRadius="10" BorderColor="Red"
Padding="0" HeightRequest="32" VerticalOptions="Start" BackgroundColor="#FFE8E8" WidthRequest="160">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="Sair_Clicou" />
</Frame.GestureRecognizers>
<StackLayout Orientation="Horizontal" HorizontalOptions="StartAndExpand" Padding="10,0,0,0">
<Image Source="Sair.png" Aspect="Fill" HeightRequest="24" WidthRequest="24" VerticalOptions="Center" HorizontalOptions="Start"
IsAnimationPlaying="True"/>
<Label Text="Sair Programa" FontSize="16" FontAttributes="Bold" VerticalTextAlignment="Center" HorizontalOptions="Start"
TextColor="Red"/>
</StackLayout>
</Frame>
</StackLayout>
<StackLayout>
</StackLayout>
<StackLayout Margin="0,-2">
<Frame x:Name="WiFi" CornerRadius="10" BorderColor="#003399"
Padding="0" HeightRequest="35" VerticalOptions="Center" BackgroundColor="White" WidthRequest="35">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="WiFi_Clicou" />
</Frame.GestureRecognizers>
<Image x:Name="imgWiFiStatus" Source="WifiVermelho.gif" Aspect="Fill" HeightRequest="24" WidthRequest="24"
VerticalOptions="Center" HorizontalOptions="Center"/>
</Frame>
</StackLayout>
</StackLayout>
</StackLayout>
<Frame BackgroundColor="Transparent" HeightRequest="25" Padding="0" VerticalOptions="Center" Margin="10,0">
<Label Text="Arquivos a Transmitir:" FontSize="15" FontAttributes="Bold"
VerticalOptions="Start" TextColor="#003399"/>
</Frame>
<StackLayout Margin="10,0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<ListView x:Name="ltvArquivoLista" SeparatorVisibility="None" SelectionMode="None" HasUnevenRows="False" IsPullToRefreshEnabled = "True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="169"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="347"></ColumnDefinition>
<ColumnDefinition Width="40"></ColumnDefinition>
</Grid.ColumnDefinitions>
<StackLayout x:Name="stlNomeMiniatura" Grid.Row="0" Grid.Column="0" Orientation="Vertical"
HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand">
<Label Text="{Binding Nome, Mode=OneWay}" FontSize="15"
VerticalOptions="Start" TextColor="#003399"/>
<Image Source="{Binding Miniatura, Mode=OneWay}" Aspect="AspectFit"
VerticalOptions="Start"
HorizontalOptions="Start"/>
</StackLayout>
<StackLayout Grid.Row="0" Grid.Column="1" Orientation="Vertical"
HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand">
<Image x:Name="cmdExcluirFoto" Source="{Binding BotaoExcluirImagem, Mode=OneWay}" Aspect="AspectFill"
HeightRequest="32" WidthRequest="32" VerticalOptions="Start" HorizontalOptions="Start">
<Image.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Tapped="Foto_Excluir_Clicou"/>
</Image.GestureRecognizers>
</Image>
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
In the .CS file I have the following piece of code that shows how the ListView ItemsSource is set with the ObservableCollection "Arquivo":
public ObservableCollection<Arquivo> Arquivos = new ObservableCollection<Arquivo>();
private List<string> ArquivosATransmitir = null;
private DateTime TestaConexaoIntervaloDtInicio = Convert.ToDateTime("2000/01/01 00:00:00");
private DateTime TestaConexaoIntervaloDtFim = Convert.ToDateTime("2000/01/01 00:00:00");
public MainPage()
{
InitializeComponent();
DeviceInfo = new DeviceInfo.CDeviceInfo();
Rotinas.File_Found("Inventario.ini", DeviceInfo.Info.Application.DataFolder, false, #"/");
if (Rotinas.INIFileName == null)
{
Rotinas.INIFileName = DeviceInfo.Info.Application.DataFolder + #"/Inventario.ini";
Rotinas.INI_Write("[SISTEMA]", "Titulo", "Inventário de Bens");
Rotinas.INI_Write("[SISTEMA]", "Subtitulo", "Transmissão de Fotos");
Rotinas.INI_Write("[SERVIDOR]", "IP", "192.168.0.22");
Rotinas.INI_Write("[SERVIDOR]", "Porta", "1234");
}
TituloSistema = Rotinas.INI_Read("[SISTEMA]", "Titulo");
Subtitulo = Rotinas.INI_Read("[SISTEMA]", "Subtitulo");
ServidorIP = Rotinas.INI_Read("[SERVIDOR]", "IP");
if (ServidorIP != "")
{
string auxPorta = Rotinas.INI_Read("[SERVIDOR]", "Porta");
if (auxPorta != null)
{
ServidorPorta = auxPorta;
}
else
{
ServidorPorta = "1234";
}
} else
{
ServidorIP = null;
ServidorPorta = null;
}
this.lblTitulo.Text = TituloSistema;
this.lblSubtitulo.Text = Subtitulo;
ConexaoServidor = new Connection();
ConexaoServidor.FileTypeName = "Fotos";
DiretorioArquivosATransmitir = DeviceInfo.Info.Application.DataFolder + #"/ArquivosATransmitir";
if (!Directory.Exists(DiretorioArquivosATransmitir))
{
Directory.CreateDirectory(DiretorioArquivosATransmitir);
}
ArquivosATransmitir = Directory.GetFiles(DiretorioArquivosATransmitir, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".jpg" }.Contains(Path.GetExtension(file))).ToList();
if (ArquivosATransmitir.Count > 0)
{
for (int Ctr = 0; Ctr <= ArquivosATransmitir.Count - 1; Ctr++)
{
GridArquivo_Incluir(ArquivosATransmitir[Ctr]);
}
}
ltvArquivoLista.ItemsSource = Arquivos;
Testa_Conexao_Servidor();
}
I would like it to appear as below:
But, the GridView is shown with the rows height fixed with the images truncated, as below:
What am I doing wrong?
Thanks in advance, sorry for my poor English.
Marcelo Camarate
You can try to modify your code as follows:
1.change the value of property HasUnevenRows from False to True for your Listview (ltvArquivoLista)
HasUnevenRows="True"
2.change Height of RowDefinition from 169 to * or Auto;
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="347"></ColumnDefinition>
<ColumnDefinition Width="40"></ColumnDefinition>
</Grid.ColumnDefinitions>

At a time only one expander expand on xamarin form

On my page there is a 4 expander ,I want to write a code for at a time one expander is expand ,What can I do for this scenario please help me ,For more clarifications I have a add image of expanders ,In this given code there is a one expander show ,but this type of a 4 expander available on my page and i want to expand one at a time
enter image description here
<StackLayout IsVisible="{Binding Synonyms,Converter={x:StaticResource CorrectionTypeVisiableConverter}}" Orientation="Vertical" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
<xct:Expander ExpandAnimationEasing="CubicIn"
ExpandAnimationLength="500"
CollapseAnimationEasing="CubicOut"
CollapseAnimationLength="500">
<xct:Expander.Header>
<Frame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BorderColor="#F0F0F0" HasShadow="False" >
<StackLayout Orientation="Horizontal" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<xct:BadgeView Text="{Binding Synonyms,Converter={StaticResource CorrectionCountBadgeConverter}}" BackgroundColor="#FADBD8" BadgePosition="TopLeft" TextColor="#E74C3C" HorizontalOptions="Start" FontSize="16" AutoHide="True" VerticalOptions="CenterAndExpand">
<Label Text=""></Label>
</xct:BadgeView>
<Label Text="{x:Static resources:AppResources.Synonyms}"
FontAttributes="Bold" VerticalOptions="CenterAndExpand"
FontSize="Medium" Style="{StaticResource MenueLableStyle}" HorizontalOptions="StartAndExpand" />
<Image Source="Expand.png"
HorizontalOptions="EndAndExpand"
VerticalOptions="CenterAndExpand">
<Image.Triggers>
<DataTrigger TargetType="Image"
Binding="{Binding Source={RelativeSource AncestorType={x:Type xct:Expander}}, Path=IsExpanded,Mode=OneTime}"
Value="True">
<Setter Property="Source"
Value="collapse.png" />
</DataTrigger>
</Image.Triggers>
</Image>
</StackLayout>
</Frame>
</xct:Expander.Header>
<xct:Expander.ContentTemplate>
<DataTemplate>
<StackLayout BindableLayout.ItemsSource="{Binding Synonyms}" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Frame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BorderColor="#F0F0F0" HasShadow="False" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackLayout Grid.Row="0" Orientation="Horizontal">
<Label Text="{Binding s}" HorizontalOptions="Start" VerticalOptions="Center">
</Label>
<Label Text="--->" HorizontalOptions="Start" VerticalOptions="Center"></Label>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<xct:BadgeView Grid.Column="0" Text="" BackgroundColor="#FADBD8" BadgePosition="TopRight" TextColor="#E74C3C" FontSize="14" HorizontalOptions="CenterAndExpand" AutoHide="True" VerticalOptions="Center" Background="#FADBD8" WidthRequest="80" HeightRequest="25">
<Label Text="{Binding c}"></Label>
</xct:BadgeView>
<ImageButton Grid.Column="0" Source="Storyedit.png"
HorizontalOptions="EndAndExpand" VerticalOptions="Center" WidthRequest="12" HeightRequest="12"/>
</Grid>
<ImageButton Source="Info.png" Command="{Binding Path=BindingContext.CorrectionInfoCommand,Source={x:Reference Name=storyView}}"
CommandParameter="{Binding .}" HorizontalOptions="EndAndExpand"/>
</StackLayout>
<Button Grid.Row="1" Text="{x:Static resources:AppResources.IgnoreButton}" Style="{StaticResource CancelButton}" VerticalOptions="EndAndExpand" HorizontalOptions="CenterAndExpand" ></Button>
<Button Grid.Row="1" Text="{x:Static resources:AppResources.AcceptButton}" Style="{StaticResource AcceptButton}" VerticalOptions="EndAndExpand" HorizontalOptions="StartAndExpand" ></Button>
<FlexLayout IsVisible="False" Grid.Row="3" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" AlignItems="Start" AlignContent="Center" Direction="Row" Wrap="Wrap" JustifyContent="Center">
<Button Text="{x:Static resources:AppResources.IgnoreButton}" Padding="5" Style="{StaticResource CancelButton}" HorizontalOptions="StartAndExpand"></Button>
<Button Text="{x:Static resources:AppResources.IgnoreAllButton}" Style="{StaticResource CancelButton}" HorizontalOptions="CenterAndExpand" Padding="5"></Button>
<Button Text="{x:Static resources:AppResources.AcceptButton}" Style="{StaticResource AcceptButton}" HorizontalOptions="StartAndExpand" Padding="5"></Button>
<Button Text="{x:Static resources:AppResources.AcceptAllButton}" Style="{StaticResource AcceptButton}" HorizontalOptions="CenterAndExpand" Padding="5"></Button>
</FlexLayout>
</Grid>
</Frame>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</DataTemplate>
</xct:Expander.ContentTemplate>
</xct:Expander>
</StackLayout>
You could binding true or false for the IsExpanded property to indicate that the Expander is expanded or collapsed.
I make a simple example for your reference.
Model:
public class Model : INotifyPropertyChanged
{
#region fields
public string _synonyms;
public string _s;
public bool _isexpand;
#endregion
public string Synonyms
{
get { return _synonyms; }
set { _synonyms = value; OnPropertyChanged("Synonyms"); }
}
public string s
{
get { return _s; }
set { _s = value; OnPropertyChanged("s"); }
}
public bool ISexpand
{
get { return _isexpand; }
set { _isexpand = value; OnPropertyChanged("ISexpand"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
ViewModel:
public class ViewModel1
{
public ObservableCollection<Model> models { get; set; }
public ViewModel1()
{
CreateCollection();
}
public void CreateCollection()
{
models = new ObservableCollection<Model>()
{
new Model(){ Synonyms="Synonym1", s="A", ISexpand=false},
new Model(){ Synonyms="Synonym2", s="B",ISexpand=false},
new Model(){ Synonyms="Synonym3", s="C",ISexpand=false},
new Model(){ Synonyms="Synonym4", s="D",ISexpand=false},
new Model(){ Synonyms="Synonym5", s="E",ISexpand=false},
};
}
}
Xaml:
<ContentPage.BindingContext>
<local:ViewModel1></local:ViewModel1>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout x:Name="stacklayout" BindableLayout.ItemsSource="{Binding models}" Orientation="Vertical" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
<BindableLayout.ItemTemplate>
<DataTemplate>
<xct:Expander IsExpanded="{Binding ISexpand}" Tapped="Expander_Tapped" >
<xct:Expander.Header>
<Label Text="{Binding Synonyms}"></Label>
</xct:Expander.Header>
<xct:Expander.ContentTemplate>
<DataTemplate>
<Label Text="{Binding s}"></Label>
</DataTemplate>
</xct:Expander.ContentTemplate>
</xct:Expander>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</ContentPage.Content>
Code behind:
public partial class Page10 : ContentPage
{
ViewModel1 viewModel1=new ViewModel1();
public Page10()
{
InitializeComponent();
}
int i = 0;
private void Expander_Tapped(object sender, EventArgs e)
{
var expander = sender as Expander;
var label = expander.Header as Label;
var list = viewModel1.models;
foreach (var item in viewModel1.models)
{
if (item.Synonyms == label.Text)
{
item.ISexpand = true;
if (i >= 1)
{
foreach (var item1 in viewModel1.models.ToList())
{
if (item1.Synonyms!= label.Text)
{
item1.ISexpand = false;
}
}
BindableLayout.SetItemsSource(stacklayout, viewModel1.models);
}
}
}
i++;
}
}
OutPut:
https://imgur.com/4D6x1yB

Xamarin Forms CollectionView TapGestureRecognizer not firing on label

I have a XF app with the following collection view defined. The 2nd label has a TapGestureRecognizer that doesn't fire DoSomethingInteresting in the model when I tap the label (trying this on Android). Can someone see what the issue is please?
A working sample can be cloned from here.
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:local="clr-namespace:SampleApp"
x:Class="SampleApp.MainPage">
<StackLayout>
<CollectionView ItemsSource="{Binding GaugeSites}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Label Grid.Column="0"
Text="{Binding Description}"
FontSize="20"
Margin="10"
TextColor="Black"
FontAttributes="Bold" />
<Label Grid.Column="1"
Margin="10"
FontSize="20"
Text="Click Me!">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding DoSomethingInteresting}" />
</Label.GestureRecognizers>
</Label>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</ContentPage>
Model
namespace SampleApp
{
public class MainPageModel : FreshBasePageModel
{
public MainPageModel() : base()
{
GaugeSites = new List<GaugeSite>();
for (var index = 1; index <= 5; index++)
{
GaugeSites.Add(new GaugeSite()
{
Description = $"Gauge Site {index}"
});
}
}
public List<GaugeSite> GaugeSites { get; set; }
public Command DoSomethingInteresting
{
get
{
return new Command(() =>
{
});
}
}
}
[AddINotifyPropertyChangedInterface]
public class GaugeSite
{
public string Description { get; set; }
}
}
Maybe this is redundant but I will take my chances. As other answers indicated you need to set the source within your TapGestureRecognizer to the name of the CollectionView. However, it is probably useful to know which GaugeSite instance was associated with the CollectionView item whose TabGestureRecognizer was tapped. To add this info add a CommandParamter, i.e.
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding BindingContext.DoSomethingInteresting,
CommandParameter="{Binding}"
Source={x:Reference YourCollectionName}}" />
</Label.GestureRecognizers>
When it comes to the command you could use
DoSomethingInteresting = new Command<GaugeSite>((a) => DoSomething(a));
in your viewmodels contructor. And the method referenced by the lambda would be
void DoSomething(GaugeSite gaugeSite)
{
// ....
}
Hope this helps
I have download your sample, please take a look the following step.
1.Binding MainpageModel for MainPage bindingContext, add this line in MainPage.cs.
this.BindingContext = new MainPageModel();
2.Name Collectionview as collection1, then modify label command.
<CollectionView x:Name="collection1" ItemsSource="{Binding GaugeSites}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Label
Grid.Column="0"
Margin="10"
FontAttributes="Bold"
FontSize="20"
Text="{Binding Description}"
TextColor="Black" />
<Label
Grid.Column="1"
Margin="10"
FontSize="20"
Text="Click Me!">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding BindingContext.DoSomethingInteresting, Source={x:Reference collection1}}" />
</Label.GestureRecognizers>
</Label>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Then you can try again.

Xamarin.Forms TapGestureRecognizer not working on IOS

I have a very simple Xamarin.Forms app. It's just for testing, and at the moment is just supposed to display messages when different boxes on the screen are tapped. The tap gesture isn't working though.
Here is my XAML:
<!-- Header -->
<Label Text="My Company"
TextColor="White"
FontSize="Large"
BackgroundColor="#a6192e"
HorizontalTextAlignment="Center" />
<!-- Body -->
<FlexLayout FlexLayout.Grow="1">
<!-- Content -->
<BoxView
BackgroundColor="#80225f"
FlexLayout.Grow="1" />
<Grid
BackgroundColor="#80225f"
Padding="20,50,50,20"
RowSpacing="20"
ColumnSpacing="20">
<Grid.RowDefinitions>
<RowDefinition Height="300"/>
<RowDefinition Height="300"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="280"/>
<ColumnDefinition Width="280"/>
<ColumnDefinition Width="280"/>
</Grid.ColumnDefinitions>
<BoxView
x:Name="App1Box"
BackgroundColor="Silver"
Grid.Row="0"
Grid.Column="0"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"/>
<BoxView
BackgroundColor="Gray"
Grid.Row="0"
Grid.Column="0"
HeightRequest="60"
VerticalOptions="Start"/>
<Label
Grid.Row="0"
Grid.Column="0"
HorizontalTextAlignment="Center"
TextColor="White"
FontSize="Large"
FontAttributes="Bold"
Margin="10">
App1</Label>
<BoxView
x:Name="App2Box"
BackgroundColor="Silver"
Grid.Row="0"
Grid.Column="1"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"/>
<BoxView
BackgroundColor="Gray"
Grid.Row="0"
Grid.Column="1"
HeightRequest="60"
VerticalOptions="Start"/>
<Label
Grid.Row="0"
Grid.Column="1"
HorizontalTextAlignment="Center"
TextColor="White"
FontSize="Large"
FontAttributes="Bold"
Margin="10">
App2</Label>
<BoxView
x:Name="App3Box"
BackgroundColor="Silver"
Grid.Row="0"
Grid.Column="2"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"/>
<BoxView
BackgroundColor="Gray"
Grid.Row="0"
Grid.Column="2"
HeightRequest="60"
VerticalOptions="Start"/>
<Label
Grid.Row="0"
Grid.Column="2"
HorizontalTextAlignment="Center"
TextColor="White"
FontSize="Large"
FontAttributes="Bold"
Margin="10">
App3</Label>
<Button Grid.Row="1"
Grid.Column="0"
Text="Test Tap"
Clicked="OnMealsTapped"
WidthRequest="100"
HeightRequest="100"
BackgroundColor="Lime"
TextColor="Red"/>
</Grid>
<!-- Navigation items-->
<BoxView FlexLayout.Basis="50"
FlexLayout.Order="-1"
Color="#80225f" />
<!-- Aside items -->
<BoxView FlexLayout.Basis="50"
Color="#80225f" />
</FlexLayout>
<!-- Footer -->
<Label Text="Test App"
FontSize="Large"
BackgroundColor="Gray"
HorizontalTextAlignment="Center" />
</FlexLayout>
</ContentPage.Content>
And here is my C#:
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace TESTAPP
{
public partial class MyPage : ContentPage
{
public MyPage()
{
InitializeComponent();
var App1TapHandler = new TapGestureRecognizer();
var App2TapHandler = new TapGestureRecognizer();
var App3TapHandler = new TapGestureRecognizer();
App1TapHandler.NumberOfTapsRequired = 1;
App1TapHandler.Tapped += OnApp1Tapped;
App2TapHandler.NumberOfTapsRequired = 1;
App2TapHandler.Tapped += OnApp2Tapped;
App3TapHandler.NumberOfTapsRequired = 1;
App3TapHandler.Tapped += OnApp3Tapped;
App1Box.GestureRecognizers.Add(App1BoxTapHandler);
App2Box.GestureRecognizers.Add(App2BoxTapHandler);
App3Box.GestureRecognizers.Add(App3BoxTapHandler);
}
private void OnApp1Tapped(object sender, EventArgs e)
{
DisplayAlert("App1","Lets use App1","OK");
}
private void OnApp2Tapped(object sender, EventArgs e)
{
DisplayAlert("App2", "Lets use App2", "OK");
}
private void OnApp3Tapped(object sender, EventArgs e)
{
DisplayAlert("App3", "Lets use App3", "OK");
}
}
}
Button is there for testing. When tapping button I get the test alert message. Nothing happens when tapping any of the BoxViews.
Why is that not working?
Your problem isn't related to the TapGesture, but you have 2 Boxviews overlapping.
So you will have to add the InputTransparent in the BoxViews that aren't receiving any input:
<BoxView
x:Name="App1Box"
BackgroundColor="Silver"
Grid.Row="0"
Grid.Column="0"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"/>
<BoxView
InputTransparent="true" <!-- Here -->
BackgroundColor="Gray"
Grid.Row="0"
Grid.Column="0"
HeightRequest="60"
VerticalOptions="Start"/>
Repeat for the remaining.
Try to invoke the code in the event handlers on the main thread.
Device.BeginInvokeOnMainThread(() =>
{
//Run the code here.
});

Resources