How to wrap a button click event to the right ViewCell - c#

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"

Related

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
}
}

ChartView within StackLayout cuts off Chart

Here is my code:
List<Entry> entries = new List<Entry>
{
new Entry(7)
{
Color = SKColor.Parse("#166DA3"),
},
new Entry(3)
{
Color = SKColors.Transparent,
}
};
public RoundScore2()
{
Content = _contentLayout; // layout inherited from a different class
Label congrats = new Label
{
Text = "Congratulations!",
FontAttributes = FontAttributes.Bold,
FontSize = 30,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Start,
TextColor = Color.Black
};
_contentStack.Children.Add(congrats); // _contentStack inherited from same class, _contentStack is added to _contentLayout
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HeightRequest = 80
};
_contentStack.Children.Add(Chart1);
Chart1.Chart = new DonutChart() { Entries = entries, HoleRadius = 5 };
Button nextRound = new Button
{
Text = "Start Round " + roundCounter.ToString(),
Margin = new Thickness(10, 20, 10, 10),
TextColor = Color.Black,
BackgroundColor = Color.FromHex("48AADF"),
FontFamily = "Source Sans Pro",
FontSize = 20,
FontAttributes = FontAttributes.Bold,
CornerRadius = 8,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.StartAndExpand,
WidthRequest = 180
};
_contentStack.Children.Add(nextRound);
}
Stack overflow is not letting me add the photo right now ("Failed to upload image; couldn't reach imgur")...but basically, I can only see the horizontal middle section of the pie chart. There is enough space for the chart to show, but it is just cut off. I have tried setting VerticalOptions = LayoutOptions.FillAndExpand along with LayoutOptions.CenterAndExpand and no luck. Does anyone know why this is happening?
Edit: even with the Label and Button taken out, the view is still cut off.
but basically, I can only see the horizontal middle section of the pie chart.
From shared code of ChartView, I'm guessing that whether the width of chart view is too small.
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HeightRequest = 80
};
If so , you can add HorizontalOptions as follow:
ChartView Chart1 = new ChartView
{
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
HeightRequest = 80
};
In addition , also can add HorizontalOptions for StackLayout:
_contentStack.HorizontalOptions = LayoutOptions.FillAndExpand;
_contentStack.VerticalOptions = LayoutOptions.FillAndExpand;
It worked after changing VerticalOptions = LayoutOptions.Center and HorizontalOptions = LayoutOptions.Fill as well as changing HoleRadius = .5f.

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 implement method of sub item of DataTemplate of ListView in Xamarin.Forms

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);

XamarinForms RelativeLayout: Can't get relative layout to resize correctly in a row

Here is my issue:
The red block is meant to be the avatar for the person sometime, and the blue balloon a chat message. The chat message object is a RelativeLayout with a Label and an Image positioned one of top of each other, but not matter what I do, I can't get it to be centered. I only have one View:
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace TestChat
{
public partial class ChatPage : ContentPage
{
public ChatPage ()
{
this.Title = "Chat page";
InitializeComponent ();
}
void OnChatClick (object sender, EventArgs args) {
Image pic = new Image {
Source = "bubble.png",
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Aspect = Aspect.Fill
};
Label textLabel = new Label {
Text = "Hello",
TextColor = Color.White,
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.EndAndExpand
};
Frame picFrame = new Frame {
HasShadow = false,
BackgroundColor = Color.Red,
Padding = new Thickness (0),
Content = pic
};
Frame textFrame = new Frame {
HasShadow = false,
BackgroundColor = Color.Transparent,
Padding = new Thickness (0,0,15,0),
Content = textLabel
};
RelativeLayout overlayLayout = new RelativeLayout { BackgroundColor = Color.Blue, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand };
overlayLayout.Children.Add (picFrame,
xConstraint: Constraint.RelativeToParent((parent) => parent.X),
yConstraint: Constraint.RelativeToParent((parent) => parent.Y),
widthConstraint: Constraint.RelativeToParent((parent) => parent.Width-2),
heightConstraint: Constraint.RelativeToParent((parent) => parent.Height-2)
);
overlayLayout.Children.Add (textFrame,
xConstraint: Constraint.RelativeToParent((parent) => parent.X),
yConstraint: Constraint.RelativeToParent((parent) => parent.Y),
widthConstraint: Constraint.RelativeToParent((parent) => parent.Width-2),
heightConstraint: Constraint.RelativeToParent((parent) => parent.Height-2)
);
Frame overlayContainerFrame = new Frame {
HasShadow = false,
BackgroundColor = Color.Red,
Padding = new Thickness(1),
HeightRequest = 100,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Content = overlayLayout
};
StackLayout horizontalLayout = new StackLayout {
Orientation = StackOrientation.Horizontal
};
BoxView avatarImage = new BoxView {
Color = Color.Red,
HeightRequest = 50,
WidthRequest = 50
};
horizontalLayout.Children.Add (avatarImage);
horizontalLayout.Children.Add (overlayContainerFrame);
ChatScrollViewStackLayout.Children.Add (horizontalLayout);
//ChatStackLayout.Children.Add (pic);
}
void CreateChatBubble() {
}
}
}
Does anyone have any ideas why I can't get the relative layout to resize accordingly so it doesn't go out of range of the screen? I tried setting its WidthConstraint to parent.With-52 to make up for the avatar taking up 50 units horizontally, but instead I get this:
I've been stuck at this for at least 8 hours now, and I'm pretty much out of ideas. Any tips would be greatly appreciated. Here is the project's git repo so you can clone it if you would like to test anything:
https://github.com/sgarcia-dev/xamarin-chat.git
Any help would be greatly appreciated, and feel free to completely ignore my code if it looks messy if you can replicate what I want. (One image on the left, and a message bubble on the right with an underlying image background)
Check out this implementation
void OnChatClick (object sender, EventArgs args) {
var pic = new Image {
Source = "bubble.png",
Aspect = Aspect.Fill
};
var textLabel = new Label {
Text = "Hello",
TextColor = Color.White,
VerticalOptions = LayoutOptions.Center,
LineBreakMode = LineBreakMode.WordWrap
};
var relativeLayout = new RelativeLayout {
BackgroundColor = Color.Navy,
// HeightRequest = 1000
};
var absoluteLayout = new AbsoluteLayout {
VerticalOptions = LayoutOptions.Center,
BackgroundColor = Color.Blue
};
var frame = new Frame {
BackgroundColor = Color.Red
};
absoluteLayout.Children.Add (pic,
new Rectangle (0, 0, 1, 1),
AbsoluteLayoutFlags.All);
absoluteLayout.Children.Add (textLabel,
new Rectangle (0.5, 0.5, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize),
AbsoluteLayoutFlags.PositionProportional);
// textLabel.SizeChanged += (object label, EventArgs e) => {
// relativeLayout.HeightRequest = textLabel.Height + 30;
// absoluteLayout.HeightRequest = textLabel.Height + 30;
// };
relativeLayout.Children.Add (frame,
heightConstraint: Constraint.RelativeToParent (parent => parent.Height),
widthConstraint: Constraint.RelativeToParent (parent => parent.Width * 0.3));
relativeLayout.Children.Add (absoluteLayout,
xConstraint: Constraint.RelativeToParent (parent => parent.Width * 0.3),
widthConstraint: Constraint.RelativeToParent (parent => parent.Width * 0.7));
ChatScrollViewStackLayout.Children.Add (relativeLayout);
}
If you need to auto-adjust height of the chat message for long text uncomment all five commented lines.

Categories

Resources