Xamarin local variable in xaml.cs and printing through the XAML file - c#

I want to be able to print properties from 'CurrentOrder' in the XAML.
Here is what I have so far:
// OrderPage.xaml.cs
public partial class OrderPage : ContentPage
{
private Order _currentOrder;
public Order CurrentOrder
{
get { return _currentOrder; }
}
public OrderPage()
{
InitializeComponent();
_currentOrder = Order.DefaultOrder;
addPin("Start", _currentOrder.PickupAddress.Latitude, _currentOrder.PickupAddress.Longitude);
addPin("End", _currentOrder.DropoffAddress.Latitude, _currentOrder.DropoffAddress.Longitude);
this.BindingContext = this;
}
public OrderPage(Order order)
{
InitializeComponent();
_currentOrder = order;
addPin("Start", _currentOrder.PickupAddress.Latitude, _currentOrder.PickupAddress.Longitude);
addPin("End", _currentOrder.DropoffAddress.Latitude, _currentOrder.DropoffAddress.Longitude);
Debug.WriteLine(_currentOrder.ToString());
this.BindingContext = this;
}
}
Here is the Order class, which has several properties with other classes.
public class Order : INotifyPropertyChanged
{
public static Order DefaultOrder
{
// I have a default order return here, but in the sake of privacy, I'm removing my test addresses
}
// event to handle changes in the order status
public event PropertyChangedEventHandler PropertyChanged;
public enum Status { Preview, NeedsDriver, WaitingDriver, InTransit, NeedsSignature, Complete, Refunded }
public string ID { get; set; }
public string Description { get; set; }
private Status _orderStatus;
public Status OrderStatus {
get
{
return _orderStatus;
}
set
{
_orderStatus = value;
// tell the view that the order status has changed
OnPropertyChanged("OrderStatus");
}
}
public Contact PickupContact { get; set; }
public Contact DropoffContact { get; set; }
public Address PickupAddress { get; set; }
public Address DropoffAddress { get; set; }
public DateTime PickupTime { get; set; }
public DateTime DropoffTime { get; set; }
// Formatted Pickup and Dropoff Times
public string PickupTimeFormatted
{
get { return PickupTime.ToString("g"); }
}
public string DropoffTimeFormatted
{
get { return DropoffTime.ToString("g"); }
}
public Order()
{
}
// Handler to tell the view that the order status has changed
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public override string ToString()
{
return string.Format("[Order: ID={0}, Description={1}, OrderStatus={2}, PickupContact={3}, DropoffContact={4}, PickupAddress={5}, DropoffAddress={6}, PickupTime={7}, DropoffTime={8}, PickupTimeFormatted={9}, DropoffTimeFormatted={10}]", ID, Description, OrderStatus, PickupContact, DropoffContact, PickupAddress, DropoffAddress, PickupTime, DropoffTime, PickupTimeFormatted, DropoffTimeFormatted);
}
}
Finally, the 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:maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
x:Class="Divco.OrderPage"
Title="Order">
<ContentPage.BindingContext>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout Spacing="10" x:Name="layout" VerticalOptions="FillAndExpand">
<StackLayout>
<maps:Map WidthRequest="320"
HeightRequest="150"
x:Name="MyMap"
IsShowingUser="false"
MapType="Street" />
</StackLayout>
<StackLayout Padding="20, 20, 20, 0">
<!--<Label Content="{Binding ID, Source={StaticResource CurrentOrder}}"></Label>-->
<Label Text="{Binding ID}"
TextColor="Fuchsia" />
<Label Text="Description"
LineBreakMode="WordWrap" />
</StackLayout>
<StackLayout Padding="20, 20, 20, 0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="Pickup"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="2"
TextColor="Fuchsia"/>
<Label Text="Top Left"
Grid.Row="1"
Grid.Column="0" />
<Label Text="Top Right"
Grid.Row="1"
Grid.Column="1" />
<Label Text="Dropoff"
Grid.Row="2"
Grid.Column="0"
Grid.ColumnSpan="2"
TextColor="Fuchsia"/>
<Label Text="Bottom Left"
Grid.Row="3"
Grid.Column="0" />
<Label Text="Bottom Right"
Grid.Row="3"
Grid.Column="1" />
</Grid>
</StackLayout>
<StackLayout Padding="20, 20, 20, 20" VerticalOptions="EndAndExpand">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Text="Call X"
BackgroundColor="Fuschia"
TextColor="White"
Grid.Row="0"
Grid.Column="0"/>
<Button Text="Navigate!"
BackgroundColor="Fuschia"
TextColor="White"
Grid.Row="0"
Grid.Column="1"
Grid.ColumnSpan="2"/>
</Grid>
</StackLayout>
</StackLayout>
</ContentPage.Content>
You can see where I attempted to print the ID of the order in the XAML. All of the supporting classes for the Order have ToString(s) which return the needed information for the order page, so I'm not really worried about printing '_currentOrder.PickupAddress.Address1', for example.

your BindingContext is a reference to the current Page
this.BindingContext = this;
so your binding path would look like:
<Label Text="{Binding CurrentOrder.ID}" TextColor="Fuchsia" />

Related

Getting all objects from another object based on it's id

I have 2 classes
Terms
public class Terms
{
[PrimaryKey, AutoIncrement]
public int TermId { get; set; }
public string TermName { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public DateTime RealStart => DateTime.Parse(StartDate);
public DateTime RealEnd => DateTime.Parse(EndDate);
}
Courses
public class Courses
{
[PrimaryKey, AutoIncrement]
public int CourseId { get; set; }
public int TermId { get; set; }
public string CourseName { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public DateTime RealStart => DateTime.Parse(StartDate);
public DateTime RealEnd => DateTime.Parse(EndDate);
public string CIName { get; set; }
public string CIEmail { get; set; }
public string CIPhone { get; set; }
public string Status { get; set; }
public bool Notifications { get; set; }
public string Notes { get; set; }
}
Term 1 -
Course 1
Course 2
When selecting a course from Term 1, I'm trying to display the expanded course details for that course.
xaml
<CollectionView x:Name="CourseCollection"
ItemsSource="{Binding Courses}"
EmptyView="No Courses to display"
SelectionMode="Single"
SelectionChanged="CourseCollection_SelectionChanged">
C#
private async void CourseCollection_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var course = (Courses)e.CurrentSelection.FirstOrDefault();
if (e.CurrentSelection != null)
{
await Navigation.PushAsync(new CoursesDetail(course));
}
}
It's displaying both courses
CoursesDetail
xaml
<CollectionView x:Name="CoursesCollection"
ItemsSource="{Binding Courses}"
EmptyView="No courses to view"
SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Grid Padding="5" RowSpacing="1" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Course ID</Label>
<Label Text="{Binding CourseId}" Grid.Row="0" Grid.Column="1" FontSize="Medium" x:Name="CourseId" ></Label>
<Label Grid.Row="1" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Term ID</Label>
<Label Text="{Binding TermId}" Grid.Row="1" Grid.Column="1" FontSize="Medium" x:Name="TermId"></Label>
<Label Grid.Row="2" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Course Name</Label>
<Label x:Name="CourseName" Grid.Row="2" Grid.Column="1" FontSize="Medium" VerticalTextAlignment="Center" Text="{Binding CourseName}"></Label>
<Label Grid.Row="3" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Start Date</Label>
<Label Grid.Row="3" Grid.Column="1" FontSize="Medium" x:Name="StartDate" Text="{Binding StartDate}"></Label>
<Label Grid.Row="4" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">End Date</Label>
<Label Grid.Row="4" Grid.Column="1" FontSize="Medium" x:Name="EndDate" Text="{Binding EndDate}"></Label>
<Label Grid.Row="5" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Instructor Name</Label>
<Label x:Name="CIName" Grid.Row="5" Grid.Column="1" FontSize="Medium" VerticalTextAlignment="Center" Text="{Binding CIName}"></Label>
<Label Grid.Row="6" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Instructor Email</Label>
<Label x:Name="CIEmail" Grid.Row="6" Grid.Column="1" FontSize="Medium" VerticalTextAlignment="Center" Text="{Binding CIEmail}"></Label>
<Label Grid.Row="7" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Instructor Phone</Label>
<Label x:Name="CIPhone" Grid.Row="7" Grid.Column="1" FontSize="Medium" VerticalTextAlignment="Center" Text="{Binding CIPhone}"></Label>
<Label Grid.Row="8" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Course Status</Label>
<Label Grid.Row="8" Grid.Column="1" x:Name="Status" FontSize="Medium" Text="{Binding Status}"></Label>
<Label Grid.Row="9" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Notes</Label>
<Label x:Name="Notes" Grid.Row="9" Grid.Column="1" FontSize="Medium" Text="{Binding Notes}"></Label>
<Label Grid.Row="10" Grid.Column="0" FontSize="Medium" VerticalTextAlignment="Center">Notifications</Label>
<Label x:Name="Notifications" Grid.Row="10" Grid.Column="1" FontSize="Medium" Text="{Binding Notifications}"></Label>
</Grid>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
c#
public partial class CoursesDetail : ContentPage
{
private readonly int _selectedCourseId;
private Courses theBiggestCourses;
protected override async void OnAppearing()
{
base.OnAppearing();
CoursesCollection.ItemsSource = await database.GetCourses(_selectedCourseId);
AssessmentsCollection.ItemsSource = await database.GetAssessments(_selectedCourseId);
}
public CoursesDetail()
{
InitializeComponent();
}
public CoursesDetail(Courses courses)
{
_selectedCourseId = courses.CourseId;
InitializeComponent();
this.theBiggestCourses = courses;
}
I've tried manually passing through each text field through the constructor. I have sample data that should auto populate and thought that it was the issue, but I removed those methods and tried manually added a Term, Courses for that Term but as soon as it gets to more than 1 course, it wacks out.
EDIT - My pea sized brain theory could be that since Terms is getting passed through as an object, capturing all the elements of that object, that it's still holding onto that Term object, so when calling the Courses object, it's capturing all the courses objects for that terms object. I hope I explained that decent.
EDIT2 - GET COURSES
public static async Task<IEnumerable<Courses>> GetCourses(int termId)
{
await Init();
var courses = await db.Table<Courses>()
.Where(i => i.TermId == termId).ToListAsync();
return courses;
}
public static async Task<IEnumerable<Courses>> GetCourses()
{
await Init();
var courses = await db.Table<Courses>().ToListAsync();
return courses;
}
These are the two for GetCourses. Is it because we're passing through an int termId here and an object in the method through the constructor? Then it defaults to the unparameterized constructor, which is going to return all of them?
GetCourses expects a TermID
public static async Task<IEnumerable<Courses>> GetCourses(int termId)
{
await Init();
var courses = await db.Table<Courses>()
.Where(i => i.TermId == termId).ToListAsync();
return courses;
}
but when you call it you are passing a CourseID
CoursesCollection.ItemsSource = await database.GetCourses(_selectedCourseId);

Get list of CollectionView return Object and put in IIList of Model in xamarin.form

In Xamarin,Try to get list of items in collectionView
My Model is
public class DrugModel
{
public string Name { get; set; }
public bool IsUsed { get; set; }
public int NumberUsed { get; set; }
}
] bind CillectionView to List that returview Api, and when debugger arrive to my change event cant get data and put on my List
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DrugMissionPage : ContentPage
{
public IList<DrugModel> SelectedDrug;
public DrugMissionPage()
{
InitializeComponent();
}
private void listDrug_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedDrugList =e.CurrentSelection ;
var tyy = selectedDrugList.ToList() as IList<DrugModel>;
foreach (var item in selectedDrugList)
{
SelectedDrug.Add(item);
}
}
And this is my View
<CollectionView
x:Name="listDrug"
VerticalOptions="StartAndExpand"
SelectionMode="Multiple"
ItemsLayout="VerticalList" SelectionChanged="listDrug_SelectionChanged">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Frame Padding="10">
<Frame BackgroundColor="AliceBlue" HasShadow="True" CornerRadius="10" Padding="10" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" FontSize="Default" HorizontalOptions="StartAndExpand" Grid.Row="0" Grid.Column="0" Margin="0,10,10,0"></Label>
</StackLayout>
</Frame>
</Frame>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
}
How can I fill
public IList<DrugModel> SelectedDrug;
When debugger pass from
var tyy = selectedDrugList.ToList() as IList<DrugModel>;
foreach (var item in selectedDrugList)
{
SelectedDrug.Add(item);
}
"tyy" will be null
You could use the Cast<class> to convert List to List.
Change:
var tyy = selectedDrugList.ToList() as IList<DrugModel>;
To:
var tyy = selectedDrugList.Cast<DrugModel>();

Binding individual property based of sqlite local database

I have created a ListView with items based on data saved in database. Its computer list with few properties as name, ipAdress, port and selected. If selected = true computer is marked as default and I need to change his appearance in ListView.
I need to create a binding to property which isnt part of the table.
I have simple list of computers (XAML)
<ListView x:Name="CompListView" HasUnevenRows="true" Grid.Row="1" SeparatorColor="Black" ItemsSource="{Binding ComputerList}"
SelectedItem="{Binding SelectedComputerItem, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding ComputerName}" Grid.Row="1" Font="20" TextColor="{Binding Selected_Color}" />
<Label Text="{Binding IPAddress}" Grid.Row="0" Font="20" Grid.Column="1" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" TextColor="{Binding Selected_Color}"/>
<Label Text="{Binding Port}" Grid.Row="1" Font="13" Grid.Column="1" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" TextColor="{Binding Selected_Color}"/>
<Image Source="computerpng.png" Grid.Row="0" Grid.Column="0" WidthRequest = "24" HeightRequest = "24" HorizontalOptions = "Start"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Base computer View connected to database.
public class BaseComputerView : INotifyPropertyChanged
{
public Computer _computer;
public INavigation _navigation;
public IComputer _computerRepository;
public string ComputerName
{
get => _computer.ComputerName;
set
{
_computer.ComputerName = value;
NotifyPropertyChanged("Computer_Name");
}
}
public string IPAddress
{
get => _computer.IPAddress;
set
{
_computer.IPAddress = value;
NotifyPropertyChanged("IPAddress");
}
}
public string Port
{
get => _computer.Port;
set
{
_computer.Port = value;
NotifyPropertyChanged("Port");
}
}
public bool Selected
{
get => _computer.Selected;
set
{
_computer.Selected = value;
NotifyPropertyChanged("Selected");
}
}
Based on _Selected I added property "Selected_Color" within the same class. Goal is to change back color of controls if the item is selected.
public string Selected_Color
{
get
{
string Text_Color = string.Empty;
try
{
if (Selected == true)
{
Text_Color = "#33cc33";
}
else
{
Text_Color = "#000000";
}
}
catch (Exception ex)
{
return "#000000";
}
return Text_Color;
}
}
This code however looks up for property "Selected_Color" in Computer table, which is wrong.
use the Ignore attribute to tell SQLite to ignore your new property
[Ignore]
public string Selected_Color
alternately, you could use a ValueConverter to set the color based on the Selected property
Thanks for your answer,
I figured it out by adding Selected_Color as Computer Table property.
[Table("Computer")]
public class Computer
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string ComputerName { get; set; }
public string IPAddress { get; set; }
public string Port { get; set; }
public bool Selected { get; set; }
[Ignore]
public string Selected_Color
{
get
{
string Text_Color = string.Empty;
try
{
if (Selected == true)
{
//Green color
Text_Color = "#33cc33";
}
else
{
Text_Color = "#000000";
}
}
catch (Exception ex)
{
return "#000000";
}
return Text_Color;
}
}
}
App_ComputerList_Image
Works fine until I open one of the computers for edit and come back to computer list. What is weird is fact that I get Java exception not for the first time I do that but only for the second time. So I am able to open one of the items and came back to computer list. If I repeat that then I get this Java exception.
just wanted to add answer for everyone who would fight with similar problem, that I found a better way to do this. You can define data templates based on your property and then use it to draw your Listview like this. Difference in this case is textcolor of the labels.
<ResourceDictionary>
<DataTemplate x:Key="SelectedComputer">
<ViewCell>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding ComputerName}" Grid.Row="1" Font="20" TextColor="Green" />
<Label Text="{Binding IPAddress}" Grid.Row="0" Font="20" Grid.Column="1" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" TextColor="Green"/>
<Label Text="{Binding Port}" Grid.Row="1" Font="13" Grid.Column="1" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" TextColor="Green"/>
<Image Source="computerpng.png" Grid.Row="0" Grid.Column="0" WidthRequest = "24" HeightRequest = "24" HorizontalOptions = "Start"/>
</Grid>
</ViewCell>
</DataTemplate>
<DataTemplate x:Key="Computer">
<ViewCell>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding ComputerName}" Grid.Row="1" Font="20" TextColor="Black" />
<Label Text="{Binding IPAddress}" Grid.Row="0" Font="20" Grid.Column="1" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" TextColor="Black"/>
<Label Text="{Binding Port}" Grid.Row="1" Font="13" Grid.Column="1" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" TextColor="Black"/>
<Image Source="computerpng.png" Grid.Row="0" Grid.Column="0" WidthRequest = "24" HeightRequest = "24" HorizontalOptions = "Start"/>
</Grid>
</ViewCell>
</DataTemplate>
<local:ComputerTemplateSelector x:Key="ComputerTemplateSelector" SelectedComputer="{StaticResource SelectedComputer}" Computer="{StaticResource Computer}" />
</ResourceDictionary>
Template selector:
public class ComputerTemplateSelector : DataTemplateSelector
{
public DataTemplate SelectedComputer { get; set; }
public DataTemplate Computer { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
return ((SQLite_Database.Computer)item).Selected == true ? SelectedComputer : Computer;
}
}

Collection was modified; enumeration operation may not execute. Xamarin Forms

I have a list view in Xamarin Froms Project as :
<ListView x:Name="ExerciseList" HasUnevenRows="False" SeparatorVisibility="None" RowHeight="200">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical">
<StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
<Entry Text="{Binding ExerciseName}" HorizontalTextAlignment="Center" Focused="ExerciseName_Focused" HorizontalOptions="CenterAndExpand">
<Entry.GestureRecognizers>
<TapGestureRecognizer Tapped="ExerciseNameGestureRecognizer_Tapped"/>
</Entry.GestureRecognizers>
</Entry>
<Image IsVisible="{Binding GreenVisible}" Source="smallgreenadd.png"/>
<Image IsVisible="{Binding RedVisible}" Source="smallredremove.png"/>
</StackLayout>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Label Text="Sets : " Grid.Column="0" Grid.Row="0" HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" />
<Label Text="Weights : " Grid.Column="0" Grid.Row="1" HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" />
<Label Text="Reps: " Grid.Column="0" Grid.Row="2" HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" />
<Entry Text="{Binding Sets}" Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" />
<Entry Text="{Binding Weights}" Grid.Column="1" Grid.Row="1" HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" />
<Entry Text="{Binding Reps}" Grid.Column="1" Grid.Row="2" HorizontalTextAlignment="Center" HorizontalOptions="CenterAndExpand" />
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
This is attached to a View Modal called ExerciseViewModal. This is:
public class ExerciseViewModal : BaseViewModal
{
private List<AddExerciseModal> _addExerciseModals;
public List<AddExerciseModal> AddExerciseModals
{
get { return _addExerciseModals; }
set
{
_addExerciseModals = value;
OnPropertyChanged("AddExerciseModals");
}
}
public ExerciseViewModal()
{
_addExerciseModals = new List<AddExerciseModal>();
if (AddExerciseModals.Count == 0)
{
for (int i = 0; i < 7; i++)
{
AddExerciseModal addExerciseModal = new AddExerciseModal
{
ExerciseID = i,
ExerciseName = "Excercise " + i,
GreenVisible = false,
RedVisible = true,
Sets = "2",
Reps = "10",
Weights = "10"
};
AddExerciseModals.Add(addExerciseModal);
}
AddExerciseModals[AddExerciseModals.Count - 1].GreenVisible = true;
AddExerciseModals[AddExerciseModals.Count - 1].RedVisible = false;
}
}
}
AddExerciseModal class :
public class AddExerciseModal
{
public int ExerciseID { get; set; }
public string ExerciseName { get; set; }
public string Weights { get; set; }
public string Reps { get; set; }
public string Sets { get; set; }
public bool GreenVisible { get; set; }
public bool RedVisible { get; set; }
}
Whenever I try to change the sets/reps/Weights property inside the ListView I always get an error saying:
"Collection was modified; enumeration operation may not execute."
How can I solve this?
Can you change your List to ObservableCollection and try it .That will resolve the problem.

Binding Itemsource in ListView inside of CarouselView - Xamarin

I have tried to put a ListView inside a CarouselView, but the element binding does not work.
If I comment out the ListView, the project will work fine.
The error is
Binding: 'Contenido' property not found on
'App.ViewModels.FeedListViewModel', target property:
'Xamarin.Forms.ListView.ItemsSource'
The code is as follows:
VIEWMODEL
public class Feed
{
public int IdFeed { get; set; }
public String Title { get; set; }
public bool HasNewElements { set; get; }
public ObservableCollection<NewsFeedDocument> Contenido { get; set; }
}
public class FeedListViewModel : MenuViewModel
{
public ObservableCollection<Feed> Feeds { get; set; }
public FeedListViewModel()
{
Feeds = new ObservableCollection<Feed>();
for (int i = 0; i <= 12; i++)
{
//Creamos lista de elementos Feed
NewsFeedDocument documento = new NewsFeedDocument();
documento.Titulo = "TITULO dasd dsa dsa dsa dsa";
ObservableCollection<NewsFeedDocument> ElementsX = new ObservableCollection<NewsFeedDocument>();
ElementsX.Add(documento);
Feeds.Add(new Feed
{
IdFeed = i ,Title = "SECTOR" + i,
Contenido = ElementsX
});
}
Position = 0;
}
private int _position = 0;
public int Position
{
get { return _position; }
set { _position = value; RaisePropertyChanged(() => Position); }
}
}
}
XAML
<cv:CarouselView x:Name="FeedsItemsCarousel" Grid.Row="2" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
Position="{Binding Position, Mode=TwoWay}"
ItemsSource="{Binding Feeds}">
<cv:CarouselView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!--<Image Grid.RowSpan="2" Aspect="AspectFill" Source="{Binding ImageUrl}"/>-->
<StackLayout Grid.Row="1" BackgroundColor="#80000000" Padding="12">
<Label TextColor="White" Text="{Binding Title}" FontSize="16" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
</StackLayout>
</Grid>
<StackLayout>
<ListView x:Name="FeedListItem" ItemsSource="{Binding Contenido}" RowHeight="120">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand" HorizontalOptions="Fill" BackgroundColor="White" Padding="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Titulo}" Style="{StaticResource TituloL}" Grid.Row="0" Grid.Column="0" />
</Grid>
<StackLayout Orientation="Horizontal">
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</DataTemplate>
</cv:CarouselView.ItemTemplate>

Categories