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);
Related
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;
}
}
}
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.
I'm looking for the best way to change the content of a page, without navigating to a new one.
I tried having two stacklayouts, and on a button press I'd change the IsVisible and IsEnabled properties of each stack layout. Although this worked, I was left with a small white gap at the end of each layout (I believe this is a Xamarin.Forms bug).
What would be the best way to accomplish this task? Is there anything built into Xamarin.Forms that can do this that I have missed?
Here is a little sketch design for you to see what I mean:
Before suggesting I use tabs, I'll add that I already have tabs in the application, the sketch doesn't show that though. I need this navigation to work on only ONE page.
The code I used before, that didn't work is:
(Before anybody mentions the poor naming conventions and lack of content, I had to strip it all out as it's code written for an employer.
C#:
private void Button1_Clicked(object sender, EventArgs e)
{
Content2.IsVisible = false;
Content2.IsEnabled = false;
Content1.IsVisible = true;
Content1.IsEnabled = true;
}
private void Button2_Clicked(object sender, EventArgs e)
{
Content2.IsVisible = true;
Content2.IsEnabled = true;
Content1.IsEnabled = false;
Content1.IsVisible = false;
}
XML:
<ScrollView x:Name="content1" VerticalOptions="FillAndExpand" BackgroundColor="#f2f2f2">
<StackLayout Spacing="0">
<StackLayout Orientation="Horizontal" BackgroundColor="White" Padding="20,20,20,20" HorizontalOptions="FillAndExpand">
<StackLayout>
<Label Text="text:" FontFamily="{StaticResource BoldFont}"/>
<StackLayout Orientation="Horizontal">
<Image x:Name="content1image" HeightRequest="25" WidthRequest="25"/>
<Label x:Name="content1label" FontFamily="{StaticResource Font}" FontSize="27" TextColor="#969696"/>
</StackLayout>
</StackLayout>
<StackLayout HorizontalOptions="FillAndExpand">
<Entry x:Name="content1Entry" Keyboard="Numeric" Margin="0,25,0,0" Placeholder="0.00000000" FontFamily="{StaticResource Font}" FontSize="27" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="End" TextColor="#969696"/>
<Label x:Name="content1Label2" FontSize="14" FontFamily="{StaticResource Font}" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="End" TextColor="#969696"/>
</StackLayout>
</StackLayout>
<StackLayout Padding="20,30,20,0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Label Text="content1Label3" FontFamily="{StaticResource Font}"/>
<StackLayout Orientation="Horizontal">
<Button x:Name="content1button" Image="image.png" BackgroundColor="Transparent" HorizontalOptions="Start" Margin="0" WidthRequest="25" HeightRequest="25"/>
<Entry x:Name="content1Entry2" FontFamily="{StaticResource Font}" FontSize="12" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="End"/>
</StackLayout>
</StackLayout>
<StackLayout VerticalOptions="EndAndExpand" Padding="0,-1,0,0">
<Label x:Name="content1Label4" FontSize="19" HorizontalOptions="CenterAndExpand" FontFamily="{StaticResource Font}"/>
<Label x:Name="content1Label5" FontSize="12" TextColor="#b6b6b6" HorizontalOptions="CenterAndExpand" FontFamily="{StaticResource Font}"/>
<Button x:Name="content1Button2" VerticalOptions="End" HorizontalOptions="FillAndExpand" BorderRadius="25" BackgroundColor="#2r432d" BorderColor="#2r432d" TextColor="White" FontFamily="{StaticResource Font}" FontSize="20" BorderWidth="3" Margin="10,10,10,10"/>
</StackLayout>
</StackLayout>
I have not had very much success using Stacklayouts. Grids however has a lot of customizability and in my case it expands to fill all the area that you wish for.
This is how I would do it.
Xaml
<Grid x:Name="Grid1" IsVisible="False" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
<Label FontSize="Medium" Text="Grid1 Label"/>
</Grid>
<Grid Grid.Row="1" HeightRequest="100" WidthRequest="375" VerticalOptions="StartAndExpand" HorizontalOptions="CenterAndExpand">
<Button x:Name="btnGrid1"/>
</Grid>
</Grid>
<Grid x:Name="Grid2" IsVisible="False" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
<Label FontSize="Medium" Text="Grid2 Label"/>
</Grid>
<Grid Grid.Row="1" HeightRequest="100" WidthRequest="375" VerticalOptions="StartAndExpand" HorizontalOptions="CenterAndExpand">
<Button x:Name="btnGrid2"/>
</Grid>
</Grid>
Code-behind
private void Button1_Clicked(object sender, EventArgs e)
{
Grid2.IsVisible = false;
Grid1.IsVisible = true;
}
private void Button2_Clicked(object sender, EventArgs e)
{
Grid2.IsVisible = true;
Grid1.IsVisible = false;
}
I put a ListView and a Label, immediately after it, but on screen, there is a Empty space between the ListView and the Label with the Text ms.
I would like the ListView to expand automatically, when the items are present.
Or is there an ItemsControl, like WPF?
I have this 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:local="clr-namespace:Forms"
x:Class="Forms.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<local:MyConverter x:Key="MyConverter"></local:MyConverter>
</ResourceDictionary>
</ContentPage.Resources>
<ScrollView Orientation="Vertical">
<StackLayout Padding="10,10,10,10">
<Label FontSize="20" FontAttributes="Bold">Cartão de Ponto</Label>
<Label>Nome:</Label>
<Label Text="{Binding Path=Pessoa.Nome}" />
<Label>CPF:</Label>
<Label Text="{Binding Path=Pessoa.CPF}" />
<Grid Padding="0" MinimumHeightRequest="40">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="35" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<Label FontSize="10" Text="Data" FontAttributes="Bold" VerticalTextAlignment="End" />
<Label FontSize="10" Grid.Column="1" Text="Dia" FontAttributes="Bold" VerticalTextAlignment="End" />
<Label FontSize="10" Grid.Column="2" Text="Hora Entrada" FontAttributes="Bold" VerticalTextAlignment="End" />
<Label FontSize="10" Grid.Column="3" Text="Hora Saída" FontAttributes="Bold" VerticalTextAlignment="End" />
<Label FontSize="10" Grid.Column="4" Text="Horas Trabalhadas" HorizontalTextAlignment="End" FontAttributes="Bold" />
</Grid>
<!-- HeightRequest="0"-->
<ListView x:Name="lv1" ItemsSource="{Binding Path=Pontos}"
VerticalOptions="FillAndExpand"
HasUnevenRows="False"
>
<ListView.Header>
<StackLayout HeightRequest="0" />
</ListView.Header>
<!-- ItemTemplate -->
<ListView.Footer>
<StackLayout HeightRequest="0" />
</ListView.Footer>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="35" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<Label FontSize="12" Text="{Binding Path=Data, StringFormat='{0:dd/MM/yyyy}'}" />
<Label FontSize="12" Grid.Column="1" Text="{Binding Path=DiaSemana}" />
<Label FontSize="12" Grid.Column="2" Text="{Binding Path=HoraEntrada}" />
<Label FontSize="12" Grid.Column="3" Text="{Binding Path=HoraSaida}" />
<Label FontSize="12" Grid.Column="4" Text="{Binding Path=HorasTrabalhadas, Converter={StaticResource MyConverter}}}" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<!-- Why is this White space on screen? -->
<StackLayout Orientation="Horizontal">
<Label x:Name="lbl1" />
<Label>ms</Label>
</StackLayout>
<Button x:Name="ButtonPegaCartaoPonto" Text="Carregar" />
<Label></Label>
<Label></Label>
</StackLayout>
</ScrollView>
</ContentPage>
But the ListView lv1 does not automatically expand Horizontally to fit the Items.
How to do this?
Set RowHeight property of your ListView and update height of list using code behind in your constructor like this:
lv1.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
{
if (e.PropertyName == "ItemsSource")
{
try
{
if (lv1.ItemsSource != null)
{
var tmp = (IList) lv1.ItemsSource;
lv1.HeightRequest = tmp.Count * lv1.RowHeight;
}
}
catch (Exception ex)
{
}
}
};
OR
You can also put specific heigh based on row height.
lv1.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
{
if (e.PropertyName == "ItemsSource")
{
try
{
if (lv1.ItemsSource != null)
{
var tmp = (IList) lv1.ItemsSource;
lv1.HeightRequest = tmp.Count * 40;
}
}
catch (Exception ex)
{
}
}
};
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?