How to implement method of sub item of DataTemplate of ListView in Xamarin.Forms - c#

I have ListView and I assigned DataTemplate to it. Now I have some controls in it like Button, Images and Labels. Now I want some actions on click event of that controls.
My ListView is like this-
listof_ingredients_and_lifestyleDiets = new ListView
{
BackgroundColor = Color.FromHex ("#CDBA96"),
ItemTemplate = preferenceTableCell,
SeparatorColor =Color.FromHex("#CDBA96"),
RowHeight=40,
HeightRequest=200
};
My DataTemplate is like this-
DataTemplate preferenceTableCell = new DataTemplate (() => {
var itemName = new Label {
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
WidthRequest=80,
FontSize=14,
TextColor=ColorResources.TextColor,
};
itemName.SetBinding (Label.TextProperty, "Name");
var radiobtn_allergen = new CircleImage {
BorderColor = ColorResources.commonButtonBackgroundColor,
HeightRequest = 25,
WidthRequest = 25,
Aspect = Aspect.AspectFill,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Source="radio_Check.png"
};
radiobtn_allergen.SetBinding(CircleImage.IsVisibleProperty,"isExcluded");
var radiobtn_preference = new CircleImage {
BorderColor = ColorResources.commonButtonBackgroundColor,
HeightRequest = 25,
WidthRequest = 25,
Aspect = Aspect.AspectFill,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Source="radio_uncheck.png",
};radiobtn_preference.SetBinding (CircleImage.IsVisibleProperty, "isExcluded");
var btnDelete=new Button{
Image="deleteBtn.png",
HorizontalOptions=LayoutOptions.EndAndExpand,
HeightRequest=50,
WidthRequest=30
};
StackLayout stacklayout = new StackLayout {
Spacing = 60,
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { itemName,radiobtn_allergen,radiobtn_preference,btnDelete }
};
return new ViewCell { View = stacklayout };
});
Now My question is, I want implement tap gesture for image tap and button click event for button control. How to do this?

Click handler for a button
btnDelete.Clicked += ((sender, args) => {
// perform actions here
});
attach a gesture recognizer to an Image
TapGestureRecognizer tapped = new TapGestureRecognizer();
tapped.Tapped += ((o2, e2) =>
{
// perform actions here
});
img.GestureRecognizers.Add(tapped);

Related

Rg.Plugin.Popup weird behavior

I have made side menu using Rg.Plugins.Popups for Xamarin.
Everything is ok, but appearing animation doesn't work for some reason. As you can see menu just appears out of nowhere when it should look like disappearing animation.
FilterMenuCommand = new Command(() =>
{
var contentView = new ReportsPageFilterMenuContentView(this);
PopupNavigation.Instance.PushAsync(new ReportsPageFilterMenuPopupPage(contentView, this));
});
My PopupPage class:
public partial class ReportsPageFilterMenuPopupPage : PopupPage
{
public ReportsPageFilterMenuPopupPage(ReportsPageFilterMenuContentView contentView, ReportsViewModel viewModel)
{
InitializePageComponent(contentView, viewModel);
}
protected void InitializePageComponent(ReportsPageFilterMenuContentView contentView, ReportsViewModel viewModel, float width = 340.0f)
{
BindingContext = viewModel;
var moveAnimation = new MoveAnimation
{
DurationIn = 800,
DurationOut = 600,
EasingIn = Easing.SinIn,
EasingOut = Easing.SinOut,
HasBackgroundAnimation = true,
PositionIn = MoveAnimationOptions.Right,
PositionOut = MoveAnimationOptions.Right,
};
Animation = moveAnimation;
Resources["DecimalConverter"] = new DecimalConverter();
var frame = new Frame
{
WidthRequest = width,
CornerRadius = 0,
Padding = new Thickness(24, 20, 24, 20),
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.StartAndExpand,
BackgroundColor = Color.White
};
var gridRowDefinitions = new RowDefinitionCollection
{
new RowDefinition {Height = GridLength.Auto}, new RowDefinition {Height = GridLength.Star}
};
var grid = new Grid
{
RowDefinitions = gridRowDefinitions
};
var stackLayout = new StackLayout
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White
};
Grid.SetRow(stackLayout, 0);
Grid.SetRow(contentView, 1);
var label = new Label
{
FontFamily = "Roboto",
FontAttributes = FontAttributes.Bold,
FontSize = 20,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Start,
Margin = new Thickness(1),
Text = MainResource.Filters
};
var imageButton = new ImageButton
{
Source = (FileImageSource)#"Assets/cross.png",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.EndAndExpand,
Margin = new Thickness(1),
Command = viewModel.CloseCommand
};
stackLayout.Children.Add(label);
stackLayout.Children.Add(imageButton);
grid.Children.Add(stackLayout);
grid.Children.Add(contentView);
frame.Content = grid;
Content = frame;
}
}
Xamarin.Forms version: 4.6.0.800
Rg.Plugins.Popup version: 2.0.0.3
If you have any clue or idea where to even start fixing this problem, please, share it with me in comments.
I use your code and test on the following simulators
Android phone
Android tablet
iOS iPhone
iOS iPad
It works fine , the appearing and disappearing animation works as expected .
I would suggest you update Xamarin.Forms and Rg.Plugins.Popup version package to the latest .

How can I add a SelectionChanged in a CollectionView from code?

I would like to call a function when a cell of a Collection View (created in cs) were tapped.
Here is the code:
new StackLayout { Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 200,
Children = {
new CollectionView {
HorizontalOptions = LayoutOptions.FillAndExpand,
SelectionMode = SelectionMode.Single,
ItemTemplate = MainPage.cv.ItemTemplate,
ItemsLayout = MainPage.cv.ItemsLayout,
ItemsSource = MainPage.jsonList.Where(x => x.Giorno == MainPage.day && x.Pasto == Pasto_Array[i]),
}
//.SelectionChanged +=CheckDuplicazioni_SelectionChanged;
}
}
As you can see I've tried to do using the code commented, but it doesn't work.
In XAML file I've used the SelectionChanged function and it worked, why in cs id doesn't?
Waiting for a your feedback,
thank you.
You can do it by saving the CollectionView instance in a variable
var collectionView = new CollectionView()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
SelectionMode = SelectionMode.Single,
ItemTemplate = MainPage.cv.ItemTemplate,
ItemsLayout = MainPage.cv.ItemsLayout,
ItemsSource = MainPage.jsonList.Where(x => x.Giorno == MainPage.day && x.Pasto == Pasto_Array[i]),
};
collectionView.SelectionChanged += CheckDuplicazioni_SelectionChanged;
new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 200,
Children = {
collectionView
}
};

How to trigger method in Children ImageButton in Xamarin?

I have created ImageButton, children of StackLayout and i want to activate delete method by click on it. I cant use "Clicked" so i dont know how to do that.
Content = new StackLayout
{
Children =
{
new ImageButton {Source = "/drawable/delete", HorizontalOptions = LayoutOptions.End, HeightRequest = 60, BackgroundColor = Color.Red, Padding = new Thickness(20,-5), CornerRadius = 45}
}
}
You could use TapGestureRecognizer
var imagebutton = new ImageButton {Source = "/drawable/delete", HorizontalOptions = LayoutOptions.End, HeightRequest = 60, BackgroundColor = Color.Red, Padding = new Thickness(20,-5), CornerRadius = 45}
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (s, e) => {
// handle the tap
};
imagebutton .GestureRecognizers.Add(tapGestureRecognizer);
Content = new StackLayout
{
Children =
{
imagebutton
}
}

programatically binding a listview in xamarin c#

I want to create a listview in Xamarin portable,
the item source of the listview is List<String> and my datatemplate of the listview is prepared by this function,
private DataTemplate createItemtemplate()
{
try
{
Label lbl_binding = new Label()
{
TextColor = Color.Red,
FontSize = 16,
VerticalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
lbl_binding.SetBinding(Label.TextProperty, ".");
StackLayout stkBottom = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(0),
};
stkBottom.Children.Add(lbl_binding);
ViewCell vc = new ViewCell() {
View = stkBottom
};
DataTemplate Dp = new DataTemplate(() =>
{
return vc;
});
return Dp;
}
catch (Exception ex)
{
return null;
}
}
Now, my list view is populated, but all the labels are filled with last item, I mean the no of items are rightly populated, but all the items are filled with the last item only.
what i am doing wrong here?
lstAdmin = new ListView()
{
ItemTemplate = createItemtemplate(),
};
lstadmin.Itemsource = source;
Change your listview from List to ObservableCollection. This should do the work.
Below code useful for you as reference
Take Class members:
public class Dummy
{
public string Id { get; set; }
public string Img { get; set; }
public string Title { get; set; }
public string SubTitle { get; set; }
public string Count { get; set; }
public string Status { get; set; }
}
Create One ObservableCollectionList:
ObservableCollection<Dummy> productItems = new
ObservableCollection<Dummy>();
Add Items to the ObservableCollectionList:
productItems.Add(new Dummy() { Name = "0", Img = "Avatar.png",
Title = "Total Books", SubTitle = "Desc", Count = "50", Status =
"Total" });
productItems.Add(new Dummy() { Id = "1", Img = "Avatar.png", Title
= "Out of Stock Books", SubTitle = "Desc", Count = "40", Status =
"OutStock" });
Declare ListView:
ListView listview = new ListView()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
SeparatorVisibility = SeparatorVisibility.None,
RowHeight = 30,
};
listview.ItemTemplate = new DataTemplate(typeof(cell));
listview.ItemSelected += listviewItemSelected;
Take ViewCell and design your UI in ViewCell and assign binding
public class cell : ViewCell
{
public cell()
{
Image img = new Image()
{
VerticalOptions = LayoutOptions.StartAndExpand,
};
img.SetBinding(Image.SourceProperty, new Binding("Img"));
Label lbltitle = new Label()
{
VerticalOptions = LayoutOptions.Start,
TextColor = Color.Black
};
lbltitle.SetBinding(Label.TextProperty, new
Binding("Title"));
Label lbldesc = new Label()
{
VerticalOptions = LayoutOptions.Start,
TextColor = Color.Black
};
lbldesc.SetBinding(Label.TextProperty, new
Binding("SubTitle"));
StackLayout lblstack = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { lbltitle, lbldesc },
};
BoxView boxEdit = new BoxView()
{
VerticalOptions = LayoutOptions.Start,
HorizontalOptions = LayoutOptions.End,
Color = Color.Black,
HeightRequest = 20,
WidthRequest = 10
};
tapGestureEdit.Tapped += tapGestureEditTapped;
Label lblCount = new Label()
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
TextColor = Color.Black
};
lblCount.SetBinding(Label.TextProperty, new
Binding("Count"));
StackLayout stackCount = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.EndAndExpand,
Children = { boxEdit, lblCount },
};
StackLayout stackMain = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { img, lblstack, stackCount },
Orientation = StackOrientation.Horizontal,
Margin = new Thickness(10, 10, 10, 10)
};
View = stackMain;
}
}
public class AdminCell : ViewCell
{
public AdminCell()
{
Label lbl_binding = new Label()
{
TextColor = Color.FromRgb(30, 144, 255),
FontSize = 16,
VerticalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
lbl_binding.SetBinding(Label.TextProperty, ".");
StackLayout stkBottom = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(0),
};
stkBottom.Children.Add(lbl_binding);
View = stkBottom;
}
}
this code is working for me removed the template and use this cell, i still don't understand why the data template is not working
I had the same issue and after some tests I've figured out how to not get always the last item.
You should put the Label creation ,and all the other elements you want put as ItemTemplate, inside the lambda of the DataTemplate like this (example code) :
DataTemplate itemTemplate = new DataTemplate(() =>
{
Label label = new Label()
{
Margin = new Thickness(45, 0, 0, 0),
HorizontalOptions = LayoutOptions.Start,
FontSize = (double)Xamarin.Forms.Application.Current.Resources["BodyFontSize"],
HeightRequest = 20
};
label.SetBinding(Label.TextProperty, "Name");
ViewCell templateCell = new ViewCell()
{
View = label
};
return templateCell;
});
Hope that helps (helped in my case).

How to wrap a button click event to the right ViewCell

I've created a CustomCell and puts a button on it.
http://i1068.photobucket.com/albums/u451/tasknick/Captura%20de%20Tela%202015-06-15%20as%2010.05.10_zpsit980vqh.png
public class CustomCell : ViewCell
{
public CustomCell ()
{
var Name = new Label {
TextColor = Color.Black,
FontSize = Device.GetNamedSize (NamedSize.Medium, typeof(Label)),
VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.Start,
FontFamily = Device.OnPlatform ("GillSans", "Quattrocento Sans", "Comic Sans MS")
};
Name.SetBinding (Label.TextProperty, "FirstName", BindingMode.TwoWay);
var LastName = new Label {
TextColor = Color.Gray,
FontSize = Device.GetNamedSize (NamedSize.Medium, typeof(Label)),
VerticalOptions = LayoutOptions.End, HorizontalOptions = LayoutOptions.Start
, FontFamily = Device.OnPlatform ("GillSans", "Quattrocento Sans", "Comic Sans MS")
};
LastName.SetBinding (Label.TextProperty, "LastName", BindingMode.TwoWay);
var ActionButton = new Button {
Image = Images.ActionButton,
Style = Styles.DefaultButtonStyle,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.End
};
ActionButton.SetBinding (Button.CommandProperty, "commandActionButton", BindingMode.TwoWay);
StackLayout stack = new StackLayout {
Padding = new Thickness (20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.StartAndExpand,
Children = { Name, LastName, ActionButton }
}
{CODE}
View = layout;
ActionButton.Clicked += (object sender, System.EventArgs e) => Debug.WriteLine ("asdjhadjsad");
}
}
The click event from button works. But how I know what cell this event comes?
For exemple: When I click on the button on the first cell I wanna show the text from the first cell;
Why do you handle ActionButton.Clicked instead of handling Command?
You've defined binding here
ActionButton.SetBinding (Button.CommandProperty, "commandActionButton", BindingMode.TwoWay);
So you could handle click in your view-model.
If you want to handle this event - sender should be your button's instance.
Try to use the FrameworkElement.Parent Property and cast it as the custom cell. This will give you a handle on the cell which holds the button. A rough example would be "(CustomCell)sender.Parent"

Categories

Resources