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
}
};
Related
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 .
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.
I am trying to make a gallery style grid view in Xamarin forms for iOS and Android but have an issue where layout options seem to be ignored and I get different results for iOS and Android.
Basic layout is:
frame with a border(red) containing a stack layout (pink) set to FillAndExpand for both horizontal and vertical options which contains a label at the top and an image below set to fill the rest of the stack.
The image seems to just expand outside of the stack and the frame and ignore the vertical options set.
I have tried setting these vertical options to Fill, FillAndExpand, CentreAndExpand but all have the same result.
If i remove the Stack layout and label and have the image as the only child element in the frame then it works as expected but I am required to also show a label.
The result is the same in landscape and portrait orientations.
Results on platform with iOS being the main issue here:
Code for adding an image to the grid:
var imageSource = ImageSource.FromStream(() => new MemoryStream(imageData));
var framedImage = new Frame
{
Padding = 0,
Margin = 3,
GestureRecognizers = { tapGesture },
Content = new StackLayout
{
Padding = 10,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.Pink,
Children =
{
textLabel,
new Image
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Source = imageSource,
Aspect = Aspect.AspectFit
},
}
},
BackgroundColor = StyleSheet.BackgroundColorLight,
BorderColor = StyleSheet.OutlineColorDark,
CornerRadius = 5,
HasShadow = false
};
grid.Children.Add(framedImage, columnCounter, rowCounter);
Thanks in advance!
Fixed it by doing this:
var image = new Image
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Source = imageSource,
Aspect = Aspect.AspectFit
};
var framedImage = new Frame
{
Padding = 2,
Margin = 1,
GestureRecognizers = { tapGesture },
Content = image,
HasShadow = false,
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand
};
var innergrid = new Grid
{
RowDefinitions =
{
new RowDefinition {Height = new GridLength(20, GridUnitType.Auto)},
new RowDefinition {Height = new GridLength(20, GridUnitType.Star)},
}
};
innergrid.Children.Add(textLabel, 0, 0);
innergrid.Children.Add(framedImage, 0, 1);
var frame = new Frame
{
Padding = 5,
Margin = 3,
GestureRecognizers = { tapGesture },
Content = innergrid,
BackgroundColor = StyleSheet.BackgroundColorLight,
BorderColor = StyleSheet.OutlineColorDark,
CornerRadius = 5,
HasShadow = true
};
grid.Children.Add(frame, columnCounter, rowCounter);
I might have a go with the new FlexLayout to see if i can have simpler code
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).
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);