Debugging: System.DivideByZeroException: Attempted to to divide by zero [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I can't figure out why I am getting this divide by zero exception. I'm very new to programming in general and can't figure out what I'm doing wrong. Sorry for the long code, I think I've removed about as much as possible and have it still give the exception.
Here is the C# code...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CalculationApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BreakEvenCalculation();
}
private void BreakEvenCalculation()
{
var purchaseprice = Decimal.Parse(PurchasePriceEntry.Text);
var purchaseweight = Decimal.Parse(PurchaseWeightEntry.Text);
var purchasefreight = Decimal.Parse(PurchaseFreightEntry.Text);
var medicineimplants = Decimal.Parse(MedicineImplantsEntry.Text);
var costofgain = Decimal.Parse(CostOfGainEntry.Text);
var poundstillsell = Decimal.Parse(PoundsTillSellEntry.Text);
var deathloss = Decimal.Parse(DeathLossEntry.Text);
var saleweight = Decimal.Parse(SaleWeightEntry.Text);
var salefreight = Decimal.Parse(SaleFreightEntry.Text);
var breakeven = Decimal.Parse(BreakEvenEntry.Text);
var purchasedollars = purchaseprice * purchaseweight;
var feedcost = costofgain * poundstillsell;
poundstillsell = saleweight - purchaseweight;
var costs = (purchasedollars + purchasefreight + medicineimplants + feedcost + deathloss + salefreight);
breakeven = costs / saleweight; //throws exception.... System.DivideByZeroException: Attempted to divide by zero
//breakeven = costs / (saleweight + 1); //correctly equals 1.111302549965541
//breakeven = costs * saleweight; //correctly equals 2338125.00
//breakeven = saleweight; //correctly equals 1450.00
//breakeven = costs; //correctly equals 1612.50
////////////breakeven should equal 1.112068965517241
BreakEvenEntry.Text = breakeven.ToString();
}
private void PurchasePriceEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void PurchaseWeightEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void PurchaseFreightEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void MedicineImplantsEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void CostOfGainEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void PoundsTillSellEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void DeathLossEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void SalePriceEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void SaleWeightEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
private void SaleFreightEntry_Completed(object sender, TextChangedEventArgs e)
{
BreakEvenCalculation();
}
}
And here is the xaml code...
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="CalculationApp.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CalculationApp"
xmlns:customentry="clr-namespace:CustomEntry">
<StackLayout Padding="0" BackgroundColor="AliceBlue" Orientation="Vertical">
<Label Text="CalculationApp" TextColor="Black" FontAttributes="Italic" FontSize="Large" TextDecorations="Underline" Scale="1.5"
Margin="0,15,0,10" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand"/>
<Grid ColumnSpacing="0" RowSpacing="5">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width=".6*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Text="Purchase Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="0" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap"/>
<Label Text="Purchase Weight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="1" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Purchase Freight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="2" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Medicine/Implants" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="3" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Cost of Gain" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="4" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Pounds Till Sell" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="5" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Death Loss" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="6" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Sale Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="7" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Sale Weight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="8" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Label Text="Sale Freight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
Grid.Column="0" Grid.Row="9" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<Entry x:Name="PurchasePriceEntry" Text="{Binding Source={x:Reference PurchasePriceStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" Keyboard="Numeric" ReturnType="Next" VerticalOptions="End" MaxLength="5"
TextChanged="PurchasePriceEntry_Completed"/>
<Entry x:Name="PurchaseWeightEntry" Text="{Binding Source={x:Reference PurchaseWeightStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="1" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="PurchaseWeightEntry_Completed" />
<Entry x:Name="PurchaseFreightEntry" Text="{Binding Source={x:Reference PurchaseFreightStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="2" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="PurchaseFreightEntry_Completed" />
<Entry x:Name="MedicineImplantsEntry" Text="{Binding Source={x:Reference MedicineImpantsStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="3" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="MedicineImplantsEntry_Completed" />
<Entry x:Name="CostOfGainEntry" Text="{Binding Source={x:Reference CostofGainStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="4" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="CostOfGainEntry_Completed" />
<Entry x:Name="PoundsTillSellEntry" Text="1000" TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="5" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center" IsEnabled="False" />
<Entry x:Name="DeathLossEntry" Text="{Binding Source={x:Reference DeathLossStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="6" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="DeathLossEntry_Completed" />
<Entry x:Name="SalePriceEntry" Text="{Binding Source={x:Reference SalePriceStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="7" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="SalePriceEntry_Completed" />
<Entry x:Name="SaleWeightEntry" Text="{Binding Source={x:Reference SaleWeightStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="8" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="SaleWeightEntry_Completed" />
<Entry x:Name="SaleFreightEntry" Text="{Binding Source={x:Reference SaleFreightStepper}, Path=Value}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
Grid.Column="1" Grid.Row="9" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
TextChanged="SaleFreightEntry_Completed" />
<Stepper x:Name="PurchasePriceStepper" Grid.Column="2" Grid.Row="0" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5" Minimum=".01" Increment=".01" Value="1.75" />
<Stepper x:Name="PurchaseWeightStepper" Grid.Column="2" Grid.Row="1" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="2000" Minimum="1" Increment="1" Value="550"/>
<Stepper x:Name="PurchaseFreightStepper" Grid.Column="2" Grid.Row="2" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="100" Minimum="0" Increment=".25" Value="10"/>
<Stepper x:Name="MedicineImpantsStepper" Grid.Column="2" Grid.Row="3" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="500" Minimum="0" Increment=".25" Value="25.00"/>
<Stepper x:Name="CostofGainStepper" Grid.Column="2" Grid.Row="4" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="3" Minimum="0" Increment=".01" Value="0.65"/>
<Stepper x:Name="DeathLossStepper" Grid.Column="2" Grid.Row="6" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="500" Minimum="0" Increment="1" Value="20"/>
<Stepper x:Name="SalePriceStepper" Grid.Column="2" Grid.Row="7" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5" Minimum="0" Increment=".01" Value="1.25"/>
<Stepper x:Name="SaleWeightStepper" Grid.Column="2" Grid.Row="8" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5000" Minimum="0" Increment="5" Value="1450.00"/>
<Stepper x:Name="SaleFreightStepper" Grid.Column="2" Grid.Row="9" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="100" Minimum="0" Increment=".25" Value="10"/>
</Grid>
<Grid Padding="10" ColumnSpacing="5" RowSpacing="10" VerticalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Text="Break Even" x:Name="BreakEvenLabel" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="0" Grid.Row="0" HorizontalTextAlignment="Center" VerticalOptions="Center" LineBreakMode="NoWrap" />
<Label Text="Profit" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" VerticalOptions="Center" LineBreakMode="NoWrap" />
<Entry x:Name="BreakEvenEntry" Text="125" FontSize="Large" TextColor="Black" Grid.Column="0" Grid.Row="1" FontAttributes="Bold" BackgroundColor="Ivory" IsEnabled="False" HorizontalTextAlignment="Center" VerticalOptions="Center" />
<Entry x:Name="ProfitEntry" TextColor="Black" FontSize="Large" Grid.Column="1" Grid.Row="1" FontAttributes="Bold" BackgroundColor="Ivory" IsEnabled="False" HorizontalTextAlignment="Center" VerticalOptions="Center" />
</Grid>
</StackLayout>
</ContentPage>
The exception happens on this line in C#...
breakeven = costs / saleweight;
As you can see, I've tried changing the code several different ways to try to figure out whats going on. In my mind, to get the divide by zero exception, the saleweight has to be zero but if I change the code to simply read...
breakeven = saleweight;
The Xamarin.Forms BreakEvenEntry gives me the correct sale weight...so it isn't zero right??
What am I missing? What am I doing wrong??
Thanks for the help in advance!!

'Cost' is being created as a float or double and needs to be explicitly defined as decimal to match your parsed decimal variables.
decimal costs = (purchasedollars + [...]
Here is a link on integer vs float division for C#:
"If one of the operands is decimal, another operand can be neither float nor double, because neither float nor double is implicitly convertible to decimal. You must explicitly convert the float or double operand to the decimal type."
(Conversely to the above suggestion, you may consider parsing your variables as doubles or floats. Same result: float division instead of integer division.)
I attempted to reproduce your error, but was unable. I, however, was reminded of a time in Python 2.7 where I found a similar error.

Related

Remove item using the same button

I'm having an issue figuring out how to remove an item from my project while using the same button as I use to perform another task. To sum it up, I'm working on a project where I have a bunch of events a user can like/dislike. What I'm having issues with is trying to figure out how to remove the event from my project once the user has liked the event using the 'like' button. Essentially I want the 'like' button to perform 2 things, one being when its pressed setting it to "true" which is already doing that, but also I want it to remove the event from screen once it's liked.
Here is my XAML:
<StackLayout VerticalOptions="FillAndExpand">
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image x:Name="LblEventImage"
Aspect="Fill"
HeightRequest="350" />
<BoxView BackgroundColor="Black"
HeightRequest="350"
Opacity="0.3" />
<Image Source="BackIconOrg.png"
Margin="5,40,0,0"
HorizontalOptions="Start"
VerticalOptions="Start"
Grid.Row="0">
<Image.GestureRecognizers>
<TapGestureRecognizer x:Name="ImgBack" Tapped="backButton_Clicked"/>
</Image.GestureRecognizers>
</Image>
</Grid>
<Frame VerticalOptions="FillAndExpand"
IsClippedToBounds="False"
BackgroundColor="#263A4F"
Margin="0,-40,0,0"
CornerRadius="25"
HasShadow="False">
<StackLayout Margin="0,-50,0,0">
<Grid HeightRequest="200"
VerticalOptions="Start">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*" />
<ColumnDefinition Width="6*"/>
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0"
Padding="5"
Spacing="5"
Margin="0,40,0,0">
<Label x:Name="LblEventName"
TextColor="#fc4600"
FontSize="Large"
FontFamily="TTBold"
FontAttributes="Bold"/>
<StackLayout Orientation="Horizontal"
Spacing="0">
<Frame BackgroundColor="#8B93A6"
BorderColor="#8B93A6"
Padding="8"
CornerRadius="15">
<Label TextColor="White"
x:Name="LblEventCategory"
FontFamily="TTNorms"/>
</Frame>
</StackLayout>
<StackLayout Orientation="Vertical" Grid.ColumnSpan="3">
<Label x:Name="LblEventCity"
TextColor="White"
FontFamily="TTNorms"/>
<Label x:Name="LblEventState"
TextColor="White"
FontFamily="TTNorms"/>
</StackLayout>
<!--<Label x:Name="LblLanguage"
TextColor="White" />
<Label x:Name="LblDuration"
TextColor="White" />-->
</StackLayout>
</Grid>
<Label Text="Details:"
FontSize="Medium"
Margin="0,20,0,0"
TextColor="White"
FontFamily="TTNorms"/>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.65*" />
<ColumnDefinition Width="0.35*" />
</Grid.ColumnDefinitions>
<Label Text="Scheduled Date:"
TextColor="White"
Grid.Row="0"
Grid.Column="0"
FontFamily="TTNorms"/>
<Label Text="August 20, 2021"
TextColor="#8B93A6"
Grid.Row="1"
Grid.Column="0"
FontFamily="TTNorms"/>
<Label Text="Group Size:"
TextColor="White"
Grid.Row="0"
Grid.Column="1"
FontFamily="TTNorms"/>
<Label x:Name="LblEventGroupSize"
TextColor="#8B93A6"
Grid.Row="1"
Grid.Column="1"
FontFamily="TTNorms"/>
<Label Text="Paid:"
TextColor="White"
Grid.Row="2"
Grid.Column="0"
FontFamily="TTNorms"/>
<Label x:Name="LblEventPay"
TextColor="#8B93A6"
Grid.Row="3"
Grid.Column="0"
FontFamily="TTNorms"/>
</Grid>
<BoxView BackgroundColor="#8B93A6"
HeightRequest="1" />
<Label Text="Description"
TextColor="White"
FontFamily="TTNorms"/>
<Label x:Name="LblEventDescription"
TextColor="#8B93A6"
FontFamily="TTNorms"/>
<StackLayout Orientation="Horizontal"
HorizontalOptions="Center"
VerticalOptions="Center"
Spacing="60"
Margin="0,30,0,0">
<Image Source="LikeButton.png"
HeightRequest="150">
<Image.GestureRecognizers>
<TapGestureRecognizer x:Name="likedevent" Tapped="likeButton_Clicked" />
</Image.GestureRecognizers>
</Image>
<Image Source="DislikeButton.png"
HeightRequest="150">
<Image.GestureRecognizers>
<TapGestureRecognizer x:Name="dislikeevent" Tapped="dislikeevent_Tapped"/>
</Image.GestureRecognizers>
</Image>
</StackLayout>
</StackLayout>
</Frame>
</StackLayout>
</ContentPage.Content>
CS:
public partial class MatchDetail : ContentPage
{
private Event event1;
public MatchDetail(int eventId)
{
InitializeComponent();
GetEventDetail(eventId);
}
private async void GetEventDetail(int eventId)
{
event1 = await ApiService.GetEventById(eventId);
LblEventName.Text = event1.Name;
LblEventDescription.Text = event1.Description;
LblEventCity.Text = event1.City;
LblEventImage.Source = event1.FullImageUrl;
LblEventCategory.Text = event1.Category;
LblEventState.Text = event1.State;
LblEventGroupSize.Text = event1.GroupSize.ToString();
LblEventPay.Text = event1.PayTrueFalse;
}
private async void likeButton_Clicked(object sender, EventArgs e)
{
var likedEvent = new Result()
{
Name = LblEventName.Text,
UserId = Preferences.Get("userId", 0),
LikeTrueFalse = "True"
};
if (event1.LikeTrueFalse == "True")
{
//RemoveEvent
}
var response = await ApiService.LikedEvents(likedEvent);
if (response)
{
await DisplayAlert("", "Your event has been liked", "Ok");
}
else
{
await DisplayAlert("Oops", "something went wrong", "cancel");
}
}
private void backButton_Clicked(object sender, EventArgs e)
{
Navigation.PopModalAsync();
}
in your main page
MessagingCenter.Subscribe<object, int>(this, "RemoveEvent", (sender,id) =>
{
// do whatever to remove event "id" here
});
then in your detail page, after you have marked it as a favorite
Messaging.Center.Send<object, int>(this, "RemoveEvent", eventId);

Collect the identifier of a Button in a row of a CollectionView in xamarin forms

I am developing an application in xamarin forms and I have problems accessing the event of a button that I have in a CollectionView. For each button that is selected, depending on the row it is in, it will do a different thing with the id.
My xaml code with the CollectionView is as follows:
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="250" />
<ColumnDefinition Width="85" />
<ColumnDefinition Width="70" />
<ColumnDefinition Width="70" />
</Grid.ColumnDefinitions>
<Label Grid.Column="1"
Text="{Binding id_cliente}"
TextColor="black"
VerticalOptions="CenterAndExpand"
FontAttributes="Bold" />
<Label
Grid.Column="2"
Text="{Binding categoria}"
FontAttributes="Italic"
VerticalOptions="CenterAndExpand"
TextColor="black"/>
<Label Grid.Column="3"
Text="{Binding descripcion}"
TextColor="black"
VerticalOptions="CenterAndExpand"
FontAttributes="Bold" />
<Label
Grid.Column="4"
Text="{Binding estado}"
TextColor="Yellow"
VerticalOptions="CenterAndExpand"
FontAttributes="Bold" />
<Button Grid.Column="5" Text="Confirmar" BorderColor="#2b3c3c" BorderWidth="1" FontAttributes="Bold" BackgroundColor="#4ba862" TextColor="White" HeightRequest="60" Margin="0,0,0,0" x:Name="btnconfirmar" Clicked="ButtonConfirmacion_Clicked" Command="{Binding id_trabajo}"/>
<Button Grid.Column="6" Text="Asignar" BorderColor="#2b3c3c" BorderWidth="1" FontAttributes="Bold" BackgroundColor="#4ba862" TextColor="White" HeightRequest="60" Margin="0,0,0,0" x:Name="btnasignar" Clicked="ButtonListaTrabajos_Clicked"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
And in the cs code of that page I have:
private void ButtonConfirmacion_Clicked(object sender, EventArgs e)
{
Trabajo selectedItem1 = e.CurrentSelection[0] as Trabajo;
}
This code, when that row is selected, with an OnSelectionChanged (sender, e) method if it picks up the item which has been selected.
You could use the code below to get the x:Name of button in a row.
private void ButtonConfirmacion_Clicked(object sender, EventArgs e)
{
var button = sender as Button;
var elemets = (button.Parent as Grid).Children;
foreach (var item in elemets)
{
if (item.GetType().Name == "Button")
{
var btn_name = item.StyleId;
}
}
}

Can someone tell me where I'm going wrong with Binding in Xamarin

Below I've attached snippets of my xaml & cs files. I'm trying to bind the entry boxes to the correct properties & the label is to be binded to the total property. I'm obviously going wrong somewhere I just can't put my finger on where. When using WPF I lay out my binding the same way. I've tried googling this & several videos which none seem to help my problem.
XAML
<Label Text="{Binding Total}"
TextColor="Black"
FontSize="50"
Grid.Column="1"
Grid.ColumnSpan="3"
Grid.Row="4"
Grid.RowSpan="1"
VerticalOptions="Center"
HorizontalOptions="Center"/>
<Label Text="APR Amount"
TextColor="Black"
FontSize="16"
Grid.Column="1"
Grid.ColumnSpan="3"
Grid.Row="5"
Grid.RowSpan="1"
VerticalOptions="Center"
HorizontalOptions="Center"/>
<Label Text="£APR"
TextColor="Black"
FontSize="30"
Grid.Column="1"
Grid.ColumnSpan="3"
Grid.Row="6"
Grid.RowSpan="1"
VerticalOptions="Center"
HorizontalOptions="Center"/>
<BoxView Color="CornflowerBlue"
CornerRadius="0"
Grid.Column="0"
Grid.ColumnSpan="5"
Grid.Row="7"
Grid.RowSpan="1"
WidthRequest="700"
HeightRequest="5"
VerticalOptions="Center"
HorizontalOptions="Center" />
<Label Text="Loan Amount"
TextColor="Black"
FontSize="20"
Grid.Column="0"
Grid.ColumnSpan="3"
Grid.Row="9"
Grid.RowSpan="2"
VerticalOptions="Center"
HorizontalOptions="Center"
Margin="0,0,0,0" />
<Entry Grid.Row="9"
Grid.Column="2"
Grid.ColumnSpan="3"
Grid.RowSpan="2"
WidthRequest="120"
VerticalOptions="Center"
HorizontalOptions="End"
Text="{Binding loanLength}"
Margin="0,0,45,0" />
<Label Text="Interest Rate"
TextColor="Black"
FontSize="20"
Grid.Column="0"
Grid.ColumnSpan="3"
Grid.Row="11"
Grid.RowSpan="2"
VerticalOptions="Center"
HorizontalOptions="Center"
Margin="0,0,0,0" />
<Entry Grid.Row="11"
Grid.RowSpan="2"
Grid.Column="2"
Grid.ColumnSpan="3"
WidthRequest="120"
VerticalOptions="Center"
HorizontalOptions="End"
Text="{Binding intRate}"
Margin="0,0,45,0" />
<Label Text="Loan Length (Years)"
TextColor="Black"
FontSize="20"
Grid.Column="0"
Grid.ColumnSpan="3"
Grid.Row="13"
Grid.RowSpan="2"
VerticalOptions="Center"
HorizontalOptions="Center"
Margin="0,0,0,0" />
<Entry Grid.Row="13"
Grid.RowSpan="2"
Grid.Column="2"
Grid.ColumnSpan="3"
WidthRequest="120"
VerticalOptions="Center"
HorizontalOptions="End"
Text="{Binding loanLength}"
Margin="0,0,45,0"/>
C#
private int loanAmount { get; set; }
public int Loan
{
get => loanAmount;
set
{
loanAmount = value;
OnPropertyChanged("Loan");
CalculateAPR();
}
}
private int intRate { get; set; }
public int Interest
{
get => intRate;
set
{
intRate = value;
OnPropertyChanged("Interest");
CalculateAPR();
}
}
private int loanLength { get; set; }
public int Length
{
get => loanLength;
set
{
loanLength = value;
OnPropertyChanged("Length");
CalculateAPR();
}
}
private string total { get; set; }
public string Total
{
get => total;
set
{
total = value;
OnPropertyChanged("Total");
}
}
public void CalculateAPR()
{
if (Interest != 0)
{
Total = "£" + (Loan * Length) / Interest;
}
else
{
Total = "£ -";
}
}
you need to bind to a public property like "Length" or "Interest"
and call PropertyChanged(nameof(loanLength)); for example (with private inside)
check this if you need
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-binding-basics
I created a demo to simulate your code,and it worked properly.
There are severals problems in your code:
1.We should bind a public property, for example, you can bind like this:
<Entry
Text="{Binding Loan}"
Margin="0,0,45,0" />
Instead of
<Entry
Text="{Binding loanLength}"
Margin="0,0,45,0" />
The same is true of other fields.
Replace <Entry Text="{Binding intRate }"/> with <Entry Text="{Binding Interest}"/>
and
Replace <Entry Text="{Binding loanLength }"/> with <Entry Text="{Binding Length}"/>
2.Try the following bindingContext code:
<Grid >
<Grid.BindingContext>
<local:ViewModel></local:ViewModel>
</Grid.BindingContext>
<Grid.RowDefinitions>
</Grid.RowDefinitions>
<!--other code-->
</Grid>

Identify Auto generating Rows in xamarin forms

I have created a application which create rows dynamically ( automatically ) when the user enter done ( in numeric keypad) . the first row is defined static manner and from the code behind rows will be created automatically followed by the columns according to the predefined columns in the first row .Xaml code as below.
<StackLayout>
<Label Text="SALES ORDER" FontSize="Medium" HorizontalTextAlignment="Center" TextColor="Black" BackgroundColor="White" FontAttributes="Bold" VerticalOptions="Center"></Label>
</StackLayout>
<Grid x:Name="thegrid" RowSpacing="7" ColumnSpacing="1" BackgroundColor="White">
<Grid.RowDefinitions>
<RowDefinition Height="10" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="10" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label x:Name="B1" Text = "ROUTE CODE" Grid.Row="1" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B2" Text = "" Grid.Row="1" Grid.Column="1" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>
<Label x:Name="B3" Text = "SHOP CODE" Grid.Row="1" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B4" Text = "Admin" Grid.Row="1" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>
<Label x:Name="B5" Text = "INVOICE DATE" Grid.Row="2" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<DatePicker x:Name="radDateTimePicker1" MinimumDate="01/01/1990" MaximumDate="01/01/2030" Grid.Row="2" Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center" />
<Label x:Name="B10" Text="{Binding Date, Source={x:Reference radDateTimePicker1},StringFormat='{0:d/M/yyyy HH:mm:ss}'}" Grid.Row="5" Grid.Column="1" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White" />
<!-- <Label x:Name="B15" Text = "AREA" Grid.Row="4" Grid.Column="0" FontSize="Medium" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B25" Text = "UVA" Grid.Row="4" Grid.Column="1" FontSize="Medium" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>-->
<Label x:Name="B35" Text = "SHOP NAME" Grid.Row="5" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B45" Text = "RADHA TRADERS" Grid.Row="5" Grid.Column="1" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>
<Label x:Name="B55" Text = "SALES ORDER" Grid.Row="3" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="B65" Text = "HATTON" Grid.Row="3" Grid.Column="1" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Black"/>
<Label x:Name="B7" Text = "AGENCY NAME" Grid.Row="2" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Picker x:Name="PickerListtwo" Grid.Row="2" Grid.Column="3" BackgroundColor="White" IsVisible="False" SelectedIndexChanged="PickerList_SelectedIndexChangedtwo">
<Picker.Items>
<x:String>Mohammed R</x:String>
<x:String>Sanath J</x:String>
<x:String>Rahul R</x:String>
<x:String>Mohammed I</x:String>
<x:String>Thuwan A</x:String>
<x:String>Praveen K</x:String>
<x:String>Roshan P</x:String>
</Picker.Items>
</Picker>
<Label x:Name="PickerLabeltwo" Text="CUSTOMER" FontSize="15" Grid.Row="2" Grid.Column="3" HorizontalOptions="Center" HorizontalTextAlignment="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tappedtwo"/>
</Label.GestureRecognizers>
</Label>
<!--<Label x:Name="B9" Text = "" Grid.Row="3" Grid.Column="0" FontSize="Medium" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>-->
<Label x:Name="B11" Text = "AGENCY CODE" Grid.Row="3" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White" />
<Label x:Name="outstanding" Text = "" Grid.Row="3" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Red"/>
<Label x:Name="CRTOP" Text = "AREA" Grid.Row="4" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="CRANS" Text = "" Grid.Row="4" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Red"/>
<Label x:Name="CRBAL" Text = "OPEARTION" Grid.Row="5" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="BALANS" Text = "" Grid.Row="5" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Red"/>
<Label x:Name="ADDRESSN" Text = "ADDRESS" Grid.Row="6" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="ADDRESSV" Text = "" Grid.Row="6" Grid.Column="3" FontSize="15" BackgroundColor="White" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="Red"/>
</Grid>
<Grid x:Name="controlGrid" RowSpacing="2" ColumnSpacing="1.5" BackgroundColor="Black" >
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<!--<RowDefinition Height="50" />-->
<!--<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />-->
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label x:Name="Btn_1" Text = "PRODUCT" Grid.Row="1" Grid.Column="0" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="Btn_2" Text = "QTY" Grid.Row="1" Grid.Column="2" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="Btn_3" Text = "PRICE" Grid.Row="1" Grid.Column="1" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="Btn_4" Text = "FREE ISSUE" Grid.Row="1" Grid.Column="3" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="Btn_5" Text = "UNIT TOTAL" Grid.Row="1" Grid.Column="4" FontSize="15" BackgroundColor="Gray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold" TextColor="White"/>
<Label x:Name="PickerLabelthree" Text="1 SELECT PRODUCT" FontSize="12" Grid.Row="2" Grid.Column="0" HorizontalOptions="FillAndExpand" BackgroundColor="White" TextColor="Black" HorizontalTextAlignment="Center" VerticalTextAlignment="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tappedthree"/>
</Label.GestureRecognizers>
</Label>
<Entry x:Name="Qtyone" TextChanged="SetRepairPercent" Keyboard="Numeric" Completed="Qtyone_Completed" Grid.Row="2" Grid.Column="2" BackgroundColor="White" FontSize="15" TextColor="Black" />
<Entry x:Name="Priceoneout" TextChanged="SetRepairPercent" Keyboard="Numeric" Grid.Row="2" Grid.Column="1" BackgroundColor="White" FontSize="15" TextColor="Black" />
<Label x:Name="Totone" Grid.Row="2" Grid.Column="3" BackgroundColor="White" FontSize="15" TextColor="Black" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
<Entry x:Name="TotoneR" TextChanged="SetRepairPercent" Keyboard="Numeric" Grid.Row="2" Grid.Column="4" BackgroundColor="White" FontSize="15" TextColor="Black" />
and the auto generation row code behind as below
private void Qtyone_Completed(object sender, EventArgs e)
{
AddARowToGridView();
// TotoneR.Text = "13.5";
}
int rowCount;
private void AddARowToGridView()
{
Label PickerLabelthree = new Label();
PickerLabelthree.Text = "1 SELECT PRODUCT";
PickerLabelthree.FontSize = 15;
PickerLabelthree.BackgroundColor = Color.White;
PickerLabelthree.TextColor = Color.Black;
PickerLabelthree.HorizontalOptions = LayoutOptions.FillAndExpand;
PickerLabelthree.HorizontalTextAlignment = TextAlignment.Center;
PickerLabelthree.VerticalTextAlignment = TextAlignment.Center;
// PickerLabelthree.Text = pickelabelthr;
// PickerLabelthree.GestureRecognizers.Add(new TapGestureRecognizer((view) => OnLabelClicked()));
// SalesPopup.testing = PickerLabelthree.Text;
PickerLabelthree.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = new Command(() => OnLabelClicked()),
});
//PickerLabelthree.GestureRecognizers.Add() += TapGestureRecognizer_Tappedthree;
Entry Qtyone = new Entry();
Qtyone.Keyboard = Keyboard.Numeric;
Qtyone.BackgroundColor = Color.White;
Qtyone.FontSize = 12;
Qtyone.TextColor = Color.Black;
Qtyone.TextChanged += SetRepairPercent;
Qtyone.Completed += Qtyone_Completed;
Entry Priceoneout = new Entry();
Priceoneout.TextChanged += SetRepairPercent;
Priceoneout.Keyboard = Keyboard.Numeric;
Priceoneout.BackgroundColor = Color.White;
Priceoneout.FontSize = 12;
Priceoneout.TextColor = Color.Black;
Label Totone = new Label();
Totone.BackgroundColor = Color.White;
Totone.FontSize = 12;
Totone.TextColor = Color.Black;
Totone.HorizontalTextAlignment = TextAlignment.Center;
Totone.VerticalTextAlignment = TextAlignment.Center;
Entry TotoneR = new Entry();
TotoneR.Keyboard = Keyboard.Numeric;
TotoneR.BackgroundColor = Color.White;
TotoneR.TextColor = Color.Black;
TotoneR.FontSize = 12;
TotoneR.TextChanged += SetRepairPercent;
//double _qtyoneamount;
//_qtyoneamount = this.Qtyoneans * this.Priceoneans;
//TotoneR.Text = _qtyoneamount.ToString();
controlGrid.Children.Add(PickerLabelthree, 0, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Priceoneout, 1, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Qtyone, 2, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Totone, 3, Convert.ToInt32(rowCount));
controlGrid.Children.Add(TotoneR, 4, Convert.ToInt32(rowCount));
// TotoneR.Text = "13.5";
rowCount++;
}
so the question is , i am unable to identify the details of the cells in rows creating automatically (to get the reference of the column cells) in the newly generating rows.( because the reason want to identify the new column row cells is that we need to calculate the price and quantity to calculate the total value in the last column) . Help will be highly appreciated and thank you in-advance for your support .
Although it's best to use an ObservableCollection instead, the reason your solution is not working is because you are not adding the children to the Grid in the Main/UI Thread. The Qtyone_Completed event handler creates another thread for the execution of the layout change. You can make it work by enclosing those lines in a function like this
Device.BeginInvokeOnMainThread(() =>
{
controlGrid.Children.Add(PickerLabelthree, 0, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Priceoneout, 1, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Qtyone, 2, Convert.ToInt32(rowCount));
controlGrid.Children.Add(Totone, 3, Convert.ToInt32(rowCount));
controlGrid.Children.Add(TotoneR, 4, Convert.ToInt32(rowCount));
});

Xamarin: The name 'x' does not exist in the current context

I'm new to Xamarin development and I'm hopeful there's a quick fix for this seemingly easy issue.
My Environment
Xamarin Studio Community on Mac 6.1.3 (build 19)
Xamarin.Android 7.0.2.42
Xamarin.Ios 10.3.1.7
Xcode 8.2.1
Mac OSX 10.12.1
My Issue
I have an existing xaml file from my Visual Studio Online repo. I added an x:name attribute called lblSearchText to a label control so I can access it in code behind. Code behind for the xaml allows me to access this control by the name I added without issue. However, when compiling I get
The name ‘lblSearchText’ does not exist in the current context
I’ve confirmed the following
Build Action on the XAML file is EmbeddedResource
Custom Tool property on the XAML file is MSBuild:UpdateDesignTimeXaml
My XAML EDIT: added full XAML
<?xml version="1.0" encoding="UTF-8" ?>
<common:ContentPage x:Class="MyApp.SearchAuthenticatedPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:common="clr-namespace:MyApp.Common;assembly=MyApp.Common"
xmlns:commonView="clr-namespace:MyApp.Common.Views;assembly=MyApp.Common"
xmlns:help="clr-namespace:MyApp.Helpers;assembly=MyApp"
xmlns:helpersCommon="clr-namespace:MyApp.Helpers;assembly=MyApp.Common"
xmlns:local="clr-namespace:MyApp;assembly=MyApp"
xmlns:sty="clr-namespace:MyApp.Styles;assembly=MyApp">
<common:ContentPage.Resources>
<ResourceDictionary>
<local:DistanceToStringConverter x:Key="DistanceToString" />
<local:StringToHeaderConverter x:Key="StringToHeader" />
<local:StringToUpperConverter x:Key="StringToUpper" />
<local:IsFavoriteToBackgroundColorConverter x:Key="IsFavoriteToBackgroundColor" />
</ResourceDictionary>
</common:ContentPage.Resources>
<RelativeLayout BackgroundColor="White" Padding="0">
<common:SearchBar x:Name="searchBar"
Title="{helpersCommon:Translate searchBarText}"
ClickCommand="{Binding SearchCommand}"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=Constant, Constant=50}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y}" />
<AbsoluteLayout IsVisible="{Binding IsMapVisible}"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Constant=-50}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Constant=50}">
<commonView:MapView x:Name="map"
WidthRequest="500"
HeightRequest="500"
VerticalOptions="FillAndExpand"
AbsoluteLayout.LayoutBounds="1,1,1,1"
AbsoluteLayout.LayoutFlags="All"
DirectionLocation="{ Binding DirectionLocation}"
IsVisible="{Binding IsMapVisible}"
Location="{Binding CurrentLocation}"
ShowDirection="{ Binding IsShowingDirection}"
Source="{Binding GetMapSource}"
ZoomToLocation="true" />
<Button x:Name="getDirectionButton"
AbsoluteLayout.LayoutBounds=".28,.33,100,30"
AbsoluteLayout.LayoutFlags="PositionProportional"
BackgroundColor="Transparent"
Text="" />
<Button x:Name="storeDetailsButton"
AbsoluteLayout.LayoutBounds=".70,.33,100,30"
AbsoluteLayout.LayoutFlags="PositionProportional"
BackgroundColor="Transparent"
IsVisible="false"
Text="" />
<Button x:Name="phoneButton"
AbsoluteLayout.LayoutBounds=".28,.27,100,20"
AbsoluteLayout.LayoutFlags="PositionProportional"
BackgroundColor="Transparent"
Text="" />
</AbsoluteLayout>
<ListView x:Name="list"
HeightRequest="300"
CachingStrategy="RetainElement"
Footer="{Binding .}"
HasUnevenRows="true"
IsGroupingEnabled="true"
IsVisible="{Binding IsListVisible}"
ItemsSource="{Binding FinalSearchResult}"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Constant=-47}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Constant=47}"
SeparatorColor="Transparent"
SeparatorVisibility="None">
<ListView.FooterTemplate>
<DataTemplate>
<ContentView>
<Label x:Name="lblSearchText" <!--- My Control --->
Margin="13, 10"
HorizontalOptions="Center"
IsVisible="{Binding IsEmpty}"
Style="{x:Static sty:Styles.PatientListBigLabelStyle}"
Text="{helpersCommon:Translate searchText}"
VerticalTextAlignment="Center" />
</ContentView>
</DataTemplate>
</ListView.FooterTemplate>
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<StackLayout BackgroundColor="{Binding Favorite, Converter={StaticResource IsFavoriteToBackgroundColor}}" Padding="13,15">
<Label Style="{x:Static sty:Styles.DarkLabelStyle}" Text="{Binding GroupName}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor="{Binding IsFavorite, Converter={StaticResource IsFavoriteToBackgroundColor}}"
Padding="13,16"
RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="5" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="35" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<commonView:FavoriteButton Grid.Row="0"
Grid.Column="0"
Margin="0,0,7,0"
ClickCommand="{Binding FavoriteChangedCommand}"
IsFavorite="{Binding IsFavorite}"
Style="{x:Static sty:Styles.FavoriteButtonStyle}" />
<Label Grid.Row="0"
Grid.Column="1"
FontSize="{x:Static sty:Styles.VeryLargeFontSize}"
Style="{x:Static sty:Styles.DarkBoldLabelStyle}"
Text="{Binding ShoppingCenterName}" />
<Label Grid.Row="0"
Grid.Column="2"
FontSize="{x:Static sty:Styles.VeryLargeFontSize}"
Style="{x:Static sty:Styles.DarkBoldRightLabelStyle}"
Text="{Binding DistanceInMilesFromLocation, Converter={StaticResource DistanceToString}}" />
<Label Grid.Row="2"
Grid.Column="1"
IsVisible="{Binding IsAddressVisible}"
Style="{x:Static sty:Styles.DarkLabelStyle}"
Text="{Binding Address}" />
<commonView:UnderlinedButton Grid.Row="2"
Grid.RowSpan="3"
Grid.Column="2"
HeightRequest="35"
Command="{Binding ShowDetailCommand}"
IsVisible="{Binding IsNotSomeMode}"
Style="{x:Static sty:Styles.ListUnderlinedButtonStyle}"
Text="{helpersCommon:Translate detailButtonText}"
TextAligment="TopRight" />
<Label Grid.Row="3"
Grid.Column="1"
VerticalOptions="Start"
IsVisible="{Binding IsAddressVisible}"
Style="{x:Static sty:Styles.DarkLabelStyle}"
Text="{Binding Address2}" />
<commonView:UnderlinedButton Grid.Row="4"
Grid.Column="1"
HeightRequest="35"
HorizontalOptions="StartAndExpand"
Command="{Binding CallCommand}"
Style="{x:Static sty:Styles.ListUnderlinedButtonStyle}"
Text="{Binding Phone}"
TextAligment="TopLeft" />
<commonView:ExtendedButton Grid.Row="4"
Grid.RowSpan="2"
Grid.Column="2"
HorizontalOptions="End"
VerticalOptions="Center"
Command="{Binding SomeCommand}"
IsVisible="{Binding IsSomeMode}"
Style="{x:Static sty:Styles.ActionButtonStyle}"
Text="{helpersCommon:Translate ListSomeButtonText}">
<commonView:ExtendedButton.FontSize>
<OnPlatform x:TypeArguments="x:Double"
Android="11"
iOS="13" />
</commonView:ExtendedButton.FontSize>
</commonView:ExtendedButton>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</RelativeLayout>
</common:ContentPage>
My Code Behind EDIT - added full code
using System.Linq;
using Xamarin.Forms;
using static MyApp.Helpers.UIHelper;
namespace MyApp
{
public partial class SearchAuthenticatedPage : global::MyApp.Common.ContentPage
{
public SearchAuthenticatedPage()
{
InitializeComponent();
lblSearchText.Text = "hello world!";
}
public bool IsMapShowing { get; set; }
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
var vm = BindingContext as BaseListViewModel;
if (vm != null) {
if (!ToolbarItems.Any()) {
SetSwitchToolbarItem();
}
vm.SetSwitchToolbarItem = SetSwitchToolbarItem;
}
getDirectionButton.IsVisible = false;
storeDetailsButton.IsVisible = false;
phoneButton.IsVisible = false;
map.CalloutShownCommand = new Command(OnShowCallout);
map.CalloutHidedCommand = new Command(OnHideCallout);
}
void OnHideCallout()
{
if (Device.OS == TargetPlatform.iOS) {
return;
}
getDirectionButton.IsVisible = false;
phoneButton.IsVisible = false;
}
void OnShowCallout()
{
if (Device.OS == TargetPlatform.iOS) {
return;
}
getDirectionButton.Command = map.ShowDirectionsCommand;
phoneButton.Command = map.PhoneCallCommand;
getDirectionButton.IsVisible = true;
phoneButton.IsVisible = true;
}
public void SetSwitchToolbarItem(bool isMapClicked = false)
{
var switchCommand = (BindingContext as BaseListViewModel)?.ChangeViewCommand;
var switchItem = ToolbarItems.FirstOrDefault(i => i.Priority == 0);
if (switchItem != null) {
switchItem.Text = isMapClicked ? Localize("titleListView") : Localize("titleMapView");
switchItem.Command = switchCommand;
}
else {
ToolbarItems.Add(new ToolbarItem { Text = Localize("titleMapView"), Command = switchCommand });
}
}
}
}
I think it is because it's inside a template, so it will be repeated for each item in the list and they would all have the same name. This is not possible.
Also, is there any particular reason you want to access it like this? Why not use binding to a property of the objects that you put in the ItemsSource?

Categories