Cannot reach xaml element from cs file in Xamarin.Forms - c#

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

Related

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

How to create a Pop up view in xamarin Forms

I need to create a Pop Up view that with an overlay.
I have tried with Absolute Layout to do this.
But I can not achieve navigation part here that should come from bottom to top.
This can be done in xamarin.iOS with Modal Presentation.
How can I do this in xamarin Forms.
The popup animation is more like scaling from bottom than translation. (Check the Popup animation in the android default popups in settings page)
You can achieve the navigation like effect by setting Anchor and then animating Scale property of the popup view.
You can achieve any animation of popup using the built in Xamarin animation. I have provided an example of scale from bottom right here.
Xaml for popup
<Frame
x:Name="popuplayout"
HasShadow="True"
IsVisible="False"
Scale="0"
BackgroundColor="White"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="1,1,0.5,0.5">
<StackLayout>
<Label Text="One"/>
<Label Text="Two"/>
<Label Text="Three"/>
<Label Text="Four"/>
<Label Text="Five"/>
<Label Text="Six"/>
</StackLayout>
</Frame>
cs button click for the popup animation.
private async void Button_Clicked(object sender, EventArgs e)
{
if (!this.popuplayout.IsVisible)
{
this.popuplayout.IsVisible = !this.popuplayout.IsVisible;
this.popuplayout.AnchorX = 1;
this.popuplayout.AnchorY = 1;
Animation scaleAnimation = new Animation(
f => this.popuplayout.Scale = f,
0.5,
1,
Easing.SinInOut);
Animation fadeAnimation = new Animation(
f => this.popuplayout.Opacity = f,
0.2,
1,
Easing.SinInOut);
scaleAnimation.Commit(this.popuplayout, "popupScaleAnimation", 250);
fadeAnimation.Commit(this.popuplayout, "popupFadeAnimation", 250);
}
else
{
await Task.WhenAny<bool>
(
this.popuplayout.FadeTo(0, 200, Easing.SinInOut)
);
this.popuplayout.IsVisible = !this.popuplayout.IsVisible;
}
Above code UI result.
Hope this could help you in achieving your UI.
You can use Rg.Plugins.Popup for creating wonderful popups in xamarin.forms.
Refer here https://github.com/rotorgames/Rg.Plugins.Popup
For more details https://askxammy.com/how-to-work-with-advanced-pop-ups-in-xamarin-forms/
// Install Rg.Plugins.Popup Nuget Package
//xaml code view for popup
<?xml version="1.0" encoding="utf-8" ?>
<animations:PopupPage xmlns:animations="http://rotorgames.com"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App.Modules.EmployeeTestDescriptionPopupPage"
xmlns:customControl="clr-
namespace:App.Controls">
<Frame VerticalOptions="CenterAndExpand" Margin="10,0,10,0"
HorizontalOptions="CenterAndExpand" BackgroundColor="#FFFFFF">
<StackLayout >
<StackLayout Orientation="Horizontal" BackgroundColor="#09326A"
Padding="10,10,10,10">
<Label Text="Display Description" TextColor="White" FontSize="20" >
</Label>
<Image HorizontalOptions="EndAndExpand" Margin="40,0,0,0">
<Image.Source>
<FontImageSource Glyph=""
Size="20"
Color="White"
FontFamily="{StaticResource
FontAwesomeSolid}"></FontImageSource>
</Image.Source>
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="ClosePopup_Tapped"
NumberOfTapsRequired="1"></TapGestureRecognizer>
</Image.GestureRecognizers>
</Image>
</StackLayout>
<ScrollView>
<StackLayout>
<StackLayout>
<Label x:Name="lblDescription" FontSize="14"/>
**//Body of popup will come here**
</StackLayout>
</StackLayout>
</ScrollView>
<!--Buttons Start-->
<StackLayout Orientation="Horizontal" HorizontalOptions="End">
<Button Text="Close" TextColor="White" BackgroundColor="#F46A6A"
Clicked="ClosePopup_Tapped"/>
</StackLayout>
<!--Buttons End-->
</StackLayout>
</Frame>
</animations:PopupPage>
// xaml.cs code
using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace App.Modules
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EmployeeTestDescriptionPopupPage :
PopupPage
{
public EmployeeTestDescriptionPopupPage(string
TestDescription)
{
InitializeComponent();
lblDescription.Text = TestDescription;
}
//Close Button Functionality
public async void ClosePopup_Tapped(object sender, EventArgs e)
{
await PopupNavigation.Instance.PopAsync();
}
}
}

How to add control in stacklayout of contentview in contentpage?

I am using xamarin.forms. having two projects Android and IOS.
I have one ContentView page with following code
<ContentView.Content>
<StackLayout x:Name="slMain" Padding="1" BackgroundColor="#7ABA45">
<StackLayout VerticalOptions="FillAndExpand" Padding="0,0,20,0" HeightRequest="50" HorizontalOptions="FillAndExpand">
<Label x:Name="lblTitle" VerticalOptions="CenterAndExpand" />
</StackLayout>
<StackLayout x:Name="sl" IsVisible="False" BackgroundColor="White">
</StackLayout>
</StackLayout>
</ContentView.Content>
// In Behind code(.cs file)
public ExpandCollapseStackLayout()
{
InitializeComponent();
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (s, e) =>
{
sl.IsVisible = !sl.IsVisible;
};
lblTitle.GestureRecognizers.Add(tapGestureRecognizer);
slMain.GestureRecognizers.Add(tapGestureRecognizer);
}
public string Title
{
get
{
return lblTitle.Text;
}
set
{
lblTitle.Text = value;
}
}
I want to add controls in StackLayout named "sl" of contentview in ContentPage at design time.
I dont want to add at runtime
Please suggest me how can I add Control in Contentview stacklayout?
If you want to add controls in design time simply declare them in your XAML, example:
<StackLayout x:Name="sl" IsVisible="False" BackgroundColor="White">
<!-- Add here your controls -->
<Label ... />
<Button .. />
</StackLayout>
If you want to add controls at runtime, you need to do it using your code behind page in C#. Example:
void AddControl()
{
var btn = new Button();
sl.Children.Add(btn);
}
Code for ContentView:
<ContentView.Content>
<StackLayout x:Name="slMain" Padding="1" BackgroundColor="#7ABA45" >
<StackLayout VerticalOptions="FillAndExpand" Padding="0,0,10,0" HeightRequest="50" HorizontalOptions="FillAndExpand" Orientation="Horizontal">
<Label x:Name="lblTitle" VerticalOptions="CenterAndExpand" HorizontalOptions="FillAndExpand" Margin="10,0,0,0" TextColor="White" FontAttributes="Bold" />
<Label Text="{ x:Static local:GrialShapesFont.ArrowDown }" HorizontalOptions="End" VerticalOptions="CenterAndExpand" TextColor="White" Style="{ StaticResource FontIconBase }" FontSize="26" />
</StackLayout>
<Frame Padding="10" IsVisible="False" BackgroundColor="White" x:Name="ContentFrame" OutlineColor="Black" HasShadow="False">
</Frame>
</StackLayout>
</ContentView.Content>
CS Code for ContentView:
[ContentProperty("ContainerContent")]
public partial class ExpandCollapseStackLayout : ContentView
{
public ExpandCollapseStackLayout()
{
InitializeComponent();
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (s, e) =>
{
ContentFrame.IsVisible = !ContentFrame.IsVisible;
};
lblTitle.GestureRecognizers.Add(tapGestureRecognizer);
slMain.GestureRecognizers.Add(tapGestureRecognizer);
}
public View ContainerContent
{
get { return ContentFrame.Content; }
set { ContentFrame.Content = value; }
}
public string Title
{
get
{
return lblTitle.Text;
}
set
{
lblTitle.Text = value;
}
}
}
Add Control in ContentPage:
<control:ExpandCollapseStackLayout Title="Demo" Padding="0,10,0,0">
<control:ExpandCollapseStackLayout.ContainerContent >
<StackLayout>
<Label Text="Add Content Here"></Label>
</StackLayout>
</control:ExpandCollapseStackLayout.ContainerContent>
</control:ExpandCollapseStackLayout>

Picker not showing Items

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:

Memory leak handling Xamarin.Forms

I have a memory leak issue in my application which I have created with Xamarin.Forms. My app consists of A ListView with Images. If I click on an item and come back to the ListPage I can see a memory hog in my Output window. I have tried calling GC.Collect() in OnDisappearing() of my ContentPage.
I have seen a base.Dispose() in my Android project. But I don't know how to use it.
ArticleListPage.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:converters="clr-namespace:NewsArticles.Mobile.Converters;assembly=Something.NewsArticles.Mobile"
xmlns:themes="clr-namespace:NewsArticles.Mobile.Themes;assembly=Something.NewsArticles.Mobile"
x:Class="NewsArticles.Mobile.Pages.ArticlesListPage"
Title="{Binding PageTitle, Mode=OneWay}"
BackgroundColor="{x:Static themes:ColorResources.ArticleListPageBackgroundColor}">
<RelativeLayout>
<ContentPage.Resources>
<ResourceDictionary>
<converters:BooleanNegationConverter x:Key="booleanNegationConverter" />
<converters:StringToImageSourceConverter x:Key="stringToImageSourceConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<ListView x:Name="ArticlesList"
StyleId="ArticlesList"
Grid.Row="1"
IsVisible="{Binding IsProcessing, Mode=OneWay, Converter={StaticResource booleanNegationConverter}}">
<ListView.BackgroundColor>
<OnPlatform x:TypeArguments="Color" iOS="Transparent" />
</ListView.BackgroundColor>
<ListView.RowHeight>
<OnPlatform x:TypeArguments="x:Int32" iOS="150" Android="180" WinPhone="170" />
</ListView.RowHeight>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ContentView BackgroundColor="{x:Static themes:ColorResources.ArticleListViewBackgroundColor}">
<ContentView.Padding>
<OnPlatform x:TypeArguments="Thickness"
iOS="10,5"
Android="10,10"
WinPhone="10,10" />
</ContentView.Padding>
<Grid BackgroundColor="White" Padding="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0"
Source="{Binding ImageUrl, Mode=OneWay, Converter={StaticResource stringToImageSourceConverter}}"
HorizontalOptions="FillAndExpand"
Aspect="AspectFill" />
<Grid Grid.Column="1" RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="20" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Text="{Binding Title, Mode=OneWay}"
VerticalOptions="Start"
LineBreakMode="WordWrap"
TextColor="{x:Static themes:ColorResources.MainArticleTitleColor}"
Font="{x:Static themes:FontResources.ListArticleTitle}" />
<ContentView Grid.Row="1" Padding="0,2">
<Label Text="{Binding Author, Mode=OneWay }"
TextColor="Silver"
Font="{x:Static themes:FontResources.VerySmall}" />
</ContentView>
<Label Grid.Row="2" Text="{Binding Body, Mode=OneWay}"
LineBreakMode="TailTruncation"
TextColor="Gray"
Font="{x:Static themes:FontResources.VerySmall}" />
</Grid>
</Grid>
</ContentView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
I had this problem a while back and this article solved it for me.
Basically you need to make a custom Renderer and place that in your droid project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Views.InputMethods;
using Android.Widget;
using Android.Util;
using Application.Droid.CustomControls;
using ApplicationClient.CustomControls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(ApplicationClient.CustomControls.LSImage), typeof(LSImageRenderer))]
namespace Application.Droid.CustomControls
{
public class LSImageRenderer : ImageRenderer
{
Page page;
NavigationPage navigPage;
protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
if (GetContainingViewCell(e.NewElement) != null)
{
page = GetContainingPage(e.NewElement);
if (page.Parent is TabbedPage)
{
page.Disappearing += PageContainedInTabbedPageDisapearing;
return;
}
navigPage = GetContainingNavigationPage(page);
if (navigPage != null)
navigPage.Popped += OnPagePopped;
}
else if ((page = GetContainingTabbedPage(e.NewElement)) != null)
{
page.Disappearing += PageContainedInTabbedPageDisapearing;
}
}
}
void PageContainedInTabbedPageDisapearing (object sender, EventArgs e)
{
this.Dispose(true);
page.Disappearing -= PageContainedInTabbedPageDisapearing;
}
protected override void Dispose(bool disposing)
{
Log.Info("**** LSImageRenderer *****", "Image got disposed");
base.Dispose(disposing);
}
private void OnPagePopped(object s, NavigationEventArgs e)
{
if (e.Page == page)
{
this.Dispose(true);
navigPage.Popped -= OnPagePopped;
}
}
private Page GetContainingPage(Xamarin.Forms.Element element)
{
Element parentElement = element.ParentView;
if (typeof(Page).IsAssignableFrom(parentElement.GetType()))
return (Page)parentElement;
else
return GetContainingPage(parentElement);
}
private ViewCell GetContainingViewCell(Xamarin.Forms.Element element)
{
Element parentElement = element.Parent;
if (parentElement == null)
return null;
if (typeof(ViewCell).IsAssignableFrom(parentElement.GetType()))
return (ViewCell)parentElement;
else
return GetContainingViewCell(parentElement);
}
private TabbedPage GetContainingTabbedPage(Element element)
{
Element parentElement = element.Parent;
if (parentElement == null)
return null;
if (typeof(TabbedPage).IsAssignableFrom(parentElement.GetType()))
return (TabbedPage)parentElement;
else
return GetContainingTabbedPage(parentElement);
}
private NavigationPage GetContainingNavigationPage(Element element)
{
Element parentElement = element.Parent;
if (parentElement == null)
return null;
if (typeof(NavigationPage).IsAssignableFrom(parentElement.GetType()))
return (NavigationPage)parentElement;
else
return GetContainingNavigationPage(parentElement);
}
}
}
Then Extend the Image class and place that in the PCL, or wherever your pages reside.
namespace ApplicationClient.CustomControls
{
public class LSImage : Image
{
}
}
Then you have to modify the XAML to work with this as well.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:ctrls="clr-namespace:ApplicationClient.CustomControls;assembly=ApplicationClient"
... >
<ctrls:LSImage ... />
</ContentPage>

Categories