Picker not showing Items - c#

Am new in xamarin forms,i have a picker and populated it with items but it can't display the items.here is my code.
Picker in Xaml
<StackLayout Margin="1">
<Picker x:Name="curr_picker" Title="select currency">
</Picker>
</StackLayout>
How i populated it in cs
curr_picker.Items.Add("UGX");
curr_picker.Items.Add("USD");
curr_picker.Items.Add("JPY");
Here is my full code
xaml
ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="FX2.ForexRates"
Title="Forex Rates"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".3*" />
<RowDefinition Height=".7*" />
</Grid.RowDefinitions>
<StackLayout Orientation="Vertical">
<!--Frame 1 -->
<Frame Margin="5" HasShadow="True" BackgroundColor="White" >
<Frame.OutlineColor>
<OnPlatform x:TypeArguments="Color" Android="Gray" iOS="#DCDCDC" />
</Frame.OutlineColor>
<StackLayout Orientation="Vertical">
<Image Source="searchbox.png" HorizontalOptions="EndAndExpand"/>
<Image Source="flag_uganda.png" HorizontalOptions="StartAndExpand"/>
</StackLayout>
</Frame>
<Frame Margin="5" HasShadow="True" BackgroundColor="White" >
<Frame.OutlineColor>
<OnPlatform x:TypeArguments="Color" Android="Gray" iOS="#DCDCDC" />
</Frame.OutlineColor>
<StackLayout Orientation="Vertical">
<Label Text="UGANDA" HorizontalOptions="Center" TextColor="#5dade2"/>
<Image Source="searchbox.png" HorizontalOptions="EndAndExpand"/>
<Label Text="Compare With" HorizontalOptions="Center" TextColor="#5dade2"/>
<StackLayout Margin="1">
<Picker x:Name="curr_picker" Title="select currency">
</Picker>
</StackLayout>
<Picker x:Name="option_picker" Title="BUY or SELL">
</Picker>
<Button Text="VIEW RATES" BackgroundColor="#0711a7" HorizontalOptions="FillAndExpand" TextColor="White" HeightRequest="65" Clicked="Button_Clicked"/>
</StackLayout>
</Frame>
</StackLayout>
</Grid>
</ContentPage>
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace FX2
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ForexRates : ContentPage
{
public ForexRates()
{
InitializeComponent();
curr_picker.Items.Add("UGX");
curr_picker.Items.Add("USD");
curr_picker.Items.Add("JPY");
option_picker.Items.Add("BUY");
option_picker.Items.Add("SELL");
}
private void Button_Clicked(object sender, EventArgs e)
{
//await Navigation.PushAsync(new MainActivity());
}
}
}

If you are using newest Xamarin.Forms, like version 2.5 or later, you probably should use ItemsSource instead of Items for data binding. In XAML it will look like this:
<Picker x:Name="picker">
<Picker.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>Baboon</x:String>
<x:String>Capuchin Monkey</x:String>
<x:String>Blue Monkey</x:String>
</x:Array>
</Picker.ItemsSource>
</Picker>
In CS like this:
var monkeyList = new List<string>();
monkeyList.Add("Baboon");
monkeyList.Add("Capuchin Monkey");
monkeyList.Add("Blue Monkey");
picker.ItemsSource = monkeyList;
Instead of simple string you can also use complex types, check more here:
https://developer.xamarin.com/guides/xamarin-forms/user-interface/picker/populating-itemssource/

From the docs:
However, a Picker doesn't show any data when it's first displayed. Instead, the value of its Title property is shown as a placeholder on the iOS and Android platforms:
When the Picker gains focus, its data is displayed and the user can select an item:

Related

Cannot reach xaml element from cs file in Xamarin.Forms

I have a XAML page. In this page i have x:Name="grid1", x:Name="stackY", x:Name="mylabel". I try to reach grid1 and stackY and mylabel from cs file. I write grid1.... or mylabel.... but cs file does not recognise grid1 and stackY and mylabel in cs file. It throws error as "The name 'mylable' does not exist in the current context". I am using Visual Studio 2019 and Xamarin.Forms.
<?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:XCMob"
x:Class="XCMob.testpage3"
Title ="Expendable ListView "
BackgroundColor="Bisque">
<ContentPage.BindingContext>
<local:MainListView/>
</ContentPage.BindingContext>
<ListView x:Name="list1" Margin="0,80"
ItemTapped="ListViewItem_Tabbed"
ItemsSource="{Binding Products}"
HasUnevenRows="True"
BackgroundColor="Black">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout x:Name="stackY" Padding="20">
<Label Text="{Binding Title}"
FontSize="25"
TextColor="Azure"/>
<StackLayout x:Name="stackX" IsVisible="{Binding Isvisible}"
Orientation="Horizontal"
Margin="0,0,80,0">
<Button Text="Place Order"
WidthRequest="110"
FontSize="15"
BackgroundColor="Chocolate"
TextColor="White"/>
<Grid x:Name="grid1">
<Label x:Name="mylabel" Text="....." TextColor="White" HorizontalTextAlignment="Center" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" FontSize="Large"/>
</Grid>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
CS file is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XCMob
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class testpage3 : ContentPage
{
public testpage3()
{
InitializeComponent();
}
private void ListViewItem_Tabbed(object sender, ItemTappedEventArgs e)
{
var product = e.Item as Product;
var vm = BindingContext as MainListView;
vm?.ShoworHiddenProducts(product);
}
void showit()
{
mylabel.Text = "xxxxxxx";
}
}
}

Xamarin Forms - Duplicate Toolbar Appearing On Pages Issue

I'm building a shopping cart and I have a very annoying problem with a double toolbar being displayed on my pages.
I spent several hours on this and having issues trying to fix it.
My current pages are setup like so:
MainHomePage (This contains a menu and an embedded page titled "MainHomePageDetail")
MainHomePageDetail (this contains a list of images where the user will click on it and it will take them to other pages as well.
PageBulkBuys (This is one of the pages that displays the product details etc)
Problem to be fixed.
I just want to remove the double toolbar that's currently being displayed on the homepage and also the subpages.
Note that if I were to click on one of the menu links, this problem disappears and it only shows one tool bar.
However If I click on one of the links in the homepage, it shows a double tool bar which is really strange.
I've tried a few solutions online but no luck.
Here's my code:
App.CS
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainHomePage());
}
MainHomePage XAML
<?xml version="1.0" encoding="utf-8"?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="xxxxx.MainHomePage" xmlns:pages="clr-namespace:xxxxx">
<MasterDetailPage.Master>
<pages:MainHomePageMaster x:Name="MasterPage" />
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
<NavigationPage BarBackgroundColor="Black">
<x:Arguments>
<pages:MainHomePageDetail />
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
</MasterDetailPage>
MainHomePage CS
public partial class MainHomePage : MasterDetailPage
{
public MainHomePage()
{
InitializeComponent();
MasterPage.ListView.ItemSelected += ListView_ItemSelected;
}
[Obsolete]
private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MainHomePageMenuItem;
if (item == null)
return;
if (item.Id == 10) // BulkBuys
Navigation.PushAsync(new BulkBuys());
}
}
MainHomePageDetail 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" x:Class="xxxx.MainHomePageDetail" Title="xxxx" BackgroundColor="Black">
<ContentPage.ToolbarItems>
<ToolbarItem Name="shoppingcarticon" IconImageSource="xxxxxx.png" Priority="0" Order="Primary" Activated="ShoppingCartClicked"/>
</ContentPage.ToolbarItems>
<StackLayout Padding="10">
<ScrollView HorizontalOptions="FillAndExpand">
<StackLayout>
<Image Source="xxxxx.png" WidthRequest="600" HeightRequest="50"/>
<Label x:Name="labelLoggedInUser" TextColor="White" FontAttributes="Bold" FontSize="18"></Label>
<!-- Banner 1 -->
<Frame x:Name="frame1" BackgroundColor="#2e2e2e">
<StackLayout>
<Image x:Name="Banner1Image" WidthRequest="600" HeightRequest="200">
<Image.GestureRecognizers>
<TapGestureRecognizer
Tapped="BtnBulkBargains"
NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image>
<Frame BackgroundColor="Green" HasShadow="False" Padding="5" HorizontalOptions="Center" WidthRequest="250" HeightRequest="20" CornerRadius="00">
<Label x:Name="Banner1Text" FontAttributes="Bold" FontSize="18" TextColor="White" WidthRequest="80" HorizontalTextAlignment="Center" ></Label>
</Frame>
<Label x:Name="Banner1Header" TextColor="White" HorizontalTextAlignment="Center"></Label>
</StackLayout>
</Frame>
<!-- Banner 2 -->
<Frame x:Name="frame2" BackgroundColor="#2e2e2e">
<StackLayout>
<Image x:Name="Banner2Image" WidthRequest="600" HeightRequest="125"></Image>
</StackLayout>
</Frame>
MainHomePageDetail CS
public MainHomePageDetail()
{
InitializeComponent();
}
private void ShoppingCartClicked(object sender, EventArgs e)
{
Navigation.PushAsync(new ViewFBShoppingCart());
}
BulkBuysPage 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"
x:Class="xxxx.PageBulkBuys"
Title="Bulk Buys"
BackgroundColor="Black"
NavigationPage.HasBackButton="True">
<ContentPage.ToolbarItems>
<ToolbarItem Name="shoppingcarticon" IconImageSource="xxxx.png" Priority="0" Order="Primary" Activated="ShoppingCartClicked"/>
</ContentPage.ToolbarItems>
<ContentPage.Content>
<StackLayout>
<Image Source="xxxx.png" WidthRequest="600" HeightRequest="50"/>
<ListView x:Name="productsListView"
HasUnevenRows="True"
VerticalOptions="FillAndExpand"
SeparatorVisibility="None"
ItemSelected="OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Frame HasShadow="True" Padding="20" Margin="20">
<StackLayout>
<Image Source="{Binding featured_src}"/>
<Label x:Name="labelProductTitle" Text="{Binding title}" FontSize="Medium" />
<Frame BackgroundColor="Red" Padding="5" HorizontalOptions="Center" WidthRequest="80" HeightRequest="20" CornerRadius="00">
<Label WidthRequest="40" Text="{Binding price, StringFormat='${0}'}" TextColor="White" HorizontalTextAlignment="Center"></Label>
</Frame>
</StackLayout>
</Frame>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
BulkBuysPage CS
public PageBulkBuys()
{
InitializeComponent();
}
private void ShoppingCartClicked(object sender, EventArgs e)
{
Navigation.PushAsync(new ViewFBShoppingCart());
}
Any help would greatly be appreciated.
Because you used the NavigationPage in your App.cs,it will create a toolbar for you:
MainPage = new NavigationPage(new MainHomePage());
try to change it to :
MainPage = new MainHomePage();
or use NavigationPage.SetHasNavigationBar method in your MainHomePage to hide the toolbar :
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainHomePage());
}
public MainHomePage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
MasterPage.ListView.ItemSelected += ListView_ItemSelected;
}

Xamarin.Forms Same Page Navigation

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

How to place a image in the half of a frame using Xamarin forms

I want to place a image in the half of a frame in my app , i am using xamarin forms to do this ,How can I do this
My Xaml
<StackLayout HorizontalOptions = "FillAndExpand" VerticalOptions="StartAndExpand" >
<ListView x:Name="lv_search" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" RowHeight="175" SeparatorColor="White">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<AbsoluteLayout HorizontalOptions = "FillAndExpand" VerticalOptions="StartAndExpand" >
<Frame BackgroundColor = "White" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand" Margin="20,10,0,0"
HeightRequest="75" AbsoluteLayout.LayoutBounds="0.01,0.9,1,1" AbsoluteLayout.LayoutFlags="All">
<Image Source = "img_frm" BackgroundColor="#14559a" AbsoluteLayout.LayoutBounds="0.009,0.9,0.3,0.6" AbsoluteLayout.LayoutFlags="All" />
<StackLayout Orientation = "Horizontal" HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand">
<AbsoluteLayout HorizontalOptions = "StartAndExpand" >
<Image Source="ellipse_1" VerticalOptions="CenterAndExpand" HorizontalOptions="Start" AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0.01,0.4,1,1" HeightRequest="100" WidthRequest="100" BackgroundColor="White"/>
<Image Source = "{Binding Image}" AbsoluteLayout.LayoutBounds="0.02,0.4,1,1" AbsoluteLayout.LayoutFlags="All"
HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" ></Image>
</AbsoluteLayout>
<Label x:Name="lbl_categories" HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand" Margin="10,0,0,0"
TextColor="Black" Text="{Binding Title}" LineBreakMode="WordWrap" HorizontalTextAlignment="Start"
FontSize="Medium" FontAttributes="Bold" AbsoluteLayout.LayoutBounds="0.3,0.3,1,1" AbsoluteLayout.LayoutFlags="All"/>
<Image HorizontalOptions = "EndAndExpand" VerticalOptions="Center" Source="arrow" AbsoluteLayout.LayoutBounds="0.9,0.3,0.3,0.3"
AbsoluteLayout.LayoutFlags="All" />
</StackLayout>
</Frame>
</AbsoluteLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
But it dosen't develop the design what I want.
Actually I want a design like this
But I get the design like this,how to modify the design into the above image
I hate to say this, but for the result you want to achieve, your xaml is a nightmare. Not only because you are having an excessive amount of elements in your visual tree, but also because you are using AbsoluteLayout inside a ListView.
Even though this is technically possible, it will cause your app losing performance, especially if your ListView gets populated with a lot of items.
Second, creating an image for that blue square also is a waste of memory and will cause more performance drops and ultimately probably OutOfMemoryExceptions on Android if your ListView contains many entries.
You could replace this with a custom View inheriting from a box view and using custom renderers for rendering rounded corners.
Also avoid using a StackLayout within a ListView, as it will also cause performance issues, since the StackLayout does a lot of calculations when being layouted.
As Dennis already mentioned, your way to go is using a Grid for layouting with keeping in mind, that all elements added to the grid will overlay each other in the order of how they have been added within your xaml definition.
Especially when using ListViews, try to use as less elements as possible and avoid elements which need a lot of layout passes.
Even though I am not using it in my example, I'd like to add the information, that you can also use negative margin values for advanced element positioning.
Here is a brief example, I hacked together:
<ListView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" RowHeight="80">
<ListView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<!-- quick hack to make the list view populate items without having to write model classes -->
<x:String>Entry 1</x:String>
<x:String>Entry 2</x:String>
<x:String>Entry 3</x:String>
<x:String>Entry 4</x:String>
</x:Array>
</ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" >
<BoxView BackgroundColor="LightGray" Margin="19,9,9,9" />
<Grid Margin="20,10,10,10" BackgroundColor="White">
<Label Text="{Binding .}" VerticalOptions="Center" FontSize="18" Margin="25,0,0,0"/>
<!-- insert icons, labels, etc here -->
</Grid>
<customs:RoundedBoxView BackgroundColor="DarkBlue" CornerRadius="6" WidthRequest="15" VerticalOptions="FillAndExpand" HorizontalOptions="Start" Margin="10,20,0,20" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The RoundedBoxView class looks like this:
public class RoundedBoxView : BoxView
{
readonly BindableProperty CornerRadiusProperty = BindableProperty.Create("CornerRadius", typeof(double), typeof(double), 0.0);
public double CornerRadius
{
get { return (double)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
}
This would be the custom renderer for android:
[assembly: ExportRenderer(typeof(RoundedBoxView), typeof(RoundedBoxViewRenderer))]
namespace TestApp.Droid
{
public class RoundedBoxViewRenderer : BoxRenderer
{
public RoundedBoxViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
{
base.OnElementChanged(e);
SetWillNotDraw(false);
Invalidate();
}
public override void Draw(Canvas canvas)
{
var box = Element as RoundedBoxView;
var rect = new Rect();
var paint = new Paint()
{
Color = box.BackgroundColor.ToAndroid(),
AntiAlias = true,
};
GetDrawingRect(rect);
var radius = (float)(box.CornerRadius);
canvas.DrawRoundRect(new RectF(rect), radius, radius, paint);
}
}
And for iOS:
[assembly: ExportRenderer(typeof(RoundedBoxView), typeof(RoundedBoxViewRenderer))]
namespace TestApp.iOS
{
public class RoundedBoxViewRenderer: BoxRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
{
base.OnElementChanged(e);
if (Element != null)
{
Layer.MasksToBounds = true;
UpdateCornerRadius(e.NewElement as RoundedBoxView);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == CircleView.WidthProperty.PropertyName || e.PropertyName == CircleView.HeightProperty.PropertyName)
{
UpdateCornerRadius(Element as RoundedBoxView);
}
}
void UpdateCornerRadius(RoundedBoxView box)
{
Layer.CornerRadius = (nfloat)(box.CornerRadius);
CGRect bounds = new CGRect(0, 0, box.Width, box.Width);
Layer.Bounds = bounds;
Layer.Frame = bounds;
}
}
Which will render like this:
}
You could use Grid instead of AbsoluteLayout.
I didn't test this, but try something like this:
<Grid
HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand">
<Frame
Grid.Row="0"
Grid.Column="0"
BackgroundColor="White"
HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand"
Margin="20,10,0,0"
HeightRequest="75">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image
Grid.Row="0"
Grid.Column="0"
Source="ellipse_1"
VerticalOptions="CenterAndExpand"
HorizontalOptions="Start"
HeightRequest="100"
WidthRequest="100"
BackgroundColor="White">
</Image>
<Image
Grid.Row="0"
Grid.Column="1"
Source="{Binding Image}"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand">
</Image>
<Label
Grid.Row="0"
Grid.Column="2"
x:Name="lbl_categories"
HorizontalOptions="FillAndExpand"
VerticalOptions="CenterAndExpand"
Margin="10,0,0,0"
TextColor="Black"
Text="{Binding Title}"
LineBreakMode="WordWrap"
HorizontalTextAlignment="Start"
FontSize="Medium"
FontAttributes="Bold">
</Label>
<Image
Grid.Row="0"
Grid.Column="3"
HorizontalOptions="EndAndExpand"
VerticalOptions="Center"
Source="arrow">
</Image>
</Grid>
</Frame>
<Image
Margin="10,10,0,0"
Grid.Row="0"
Grid.Column="0"
Source="img_frm"
BackgroundColor="#14559a">
</Image>
</Grid>
Because the Image is created after the Frame in your xaml, it overlaps the Frame. You may need to change the margins of the Frame and blue square shaped Image according to your needs.

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