Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 89864 articles
Browse latest View live

Setting background image based on Idiom in Xaml.

$
0
0

Hello I have this peice of code that works fine but it is in the code behind , is there a way to write that in Xaml ?

public partial class TestFormsPage : ContentPage
    {
        public TestFormsPage()
        {
            if (Device.Idiom == TargetIdiom.Tablet)
            {
                BackgroundImage = "darkBackground_Tablet.jpg";
            }
            if (Device.Idiom == TargetIdiom.Phone)
            {
                BackgroundImage = "DarkBackgroundPhone.jpg";
            }
            InitializeComponent();
        }
    }

Generic base class for a custom ContentPage

$
0
0

The last Xamarin.Forms release notes had this comment:

  • [XAML] x:TypeArguments now works at root level, fixing generic subclassing from XAML

That sounds like exactly what I'm trying to do, but I'm struggling to come up with the right syntax to make it work.

I have a base class for all of my custom pages:

public class PageBase<TViewModel> : ContentPage
    where TViewModel : ViewModel
{
    public TViewModel ViewModel { get { return BindingContext as TViewModel; } }
}

Then one of my custom pages looks something like this:

public class MyPage : PageBase<MyPageViewModel>
{
    // ...
}

The hard part is figuring out how to write MyPage.xaml. Here is what I have tried:

<?xml version="1.0" encoding="UTF-8"?>
<local:PageBase
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:App.View.Pages;assembly=App"
    x:Class="App.View.Pages.MyPage"
    x:TypeArguments="App.ViewModel.Pages.MyPageViewModel">
    <!-- ... -->
</local:PageBase>

When I build this I get a compile error because the generated MyPage.xaml.g.cs file looks like this:

public partial class MyPage : global::App.View.Pages.PageBase {
    private void InitializeComponent() {
        this.LoadFromXaml(typeof(MyPage));
    }
}

The error is that there is no type specifier for the base class. It should look like this:

public partial class MyPage : global::App.View.Pages.PageBase<global::App.ViewModel.Pages.MyPageViewModel> {
    private void InitializeComponent() {
        this.LoadFromXaml(typeof(MyPage));
    }
}

Based on the line in the release notes I believe this is possible, but I must be missing something. How can I make this do what I want it to do?

Converters not working with custom ContentPage class

$
0
0

Hi,

I've created a shared project (not PCL) and for my content pages, I'm using a custom class called: BaseContentPage.

My BaseContentPage class implements the following:

public class BaseContentPage : ContentPage, INotifyPropertyChanged

When I run my application I get the following exception:

"Type BaseContentPage not found in xmlns http://xamarin.com/schemas/2014/forms"

I have tried changing the XAML and the code behind file to implement ContentPage instead of BaseContentPage and the converters work fine.
I have also tried changing the resources dictionary to use the following:

<ContentPage.Resources> and <BaseContentPage.Resources>

Neither of which were successful.

A colleague of mine has successfully implemented converters with a custom class however, the project is set-up as a PCL.

Has anyone come across this problem before?

Error inflating class android.support.v7.widget.Toolbar after updaring to v7.AppCompat Version 23.3

$
0
0

I am creating a Xamarin Forms Project and using android.support.v7.widget.Toolbar with FormsAppCompatActivity. The code I'm posting below was working with Xamarin.Android.Support.v7.AppCompat Version: 23.0.1.3

But after I upgraded to 23.3.0 this has started throwing Android.Views.InflateException: Binary XML file line #1: Error inflating class android.support.v7.widget.toolbar exception.

Here is my code for MainActivity

[Activity(Label = "AppMob.Client", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {

        protected override void OnCreate(Bundle bundle)
        {
            FormsAppCompatActivity.ToolbarResource = Resource.Layout.toolbar;
            FormsAppCompatActivity.TabLayoutResource = Resource.Layout.tabs;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);

            Xamarin.FormsMaps.Init(this,bundle);
            GoogleAnalyticsHelper.GetGASInstance().Initialize_NativeGAS(Application.Context);  //For GA initialization
            LoadApplication(new App());
        }
}

This is my code for Resource.Layout.toolbar

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_scrollFlags="scroll|enterAlways" />

how to import namespace in XAML from another class library project?

$
0
0

I have a class library project which containes collection of Behaviors for my App.
This is one of my Behavior.

namespace MyLibrary.Xamarin.Behaviors
{
    public class NumericValidationBehavior : Behavior<Entry>
    {
    ...
    }
}

And I am consuming NumericValidationBehaviorlike below in my App.

<?xml version="1.0" encoding="utf-8" ?>
<d:ContentPageBase
             xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyAppEngine.Views.MyPage"
             xmlns:local="clr-namespace:MyLibrary.Xamarin.Behaviors;"
             xmlns:d="clr-namespace:MyLibrary.Xamarin.Controls.Pages;"
             Title="My details">
        ...
        <Entry Placeholder="Enter a System.Double">
            <Entry.Behaviors>
                <local:NumericValidationBehavior />
            </Entry.Behaviors>
        </Entry>
        ...
</d:ContentPageBase>

But I got following Runtime exception.

Xamarin.Forms.Xaml.XamlParseException: Position 91:12.
Type local:NumericValidationBehavior not found in xmlns clr-namespace:MyLibrary.Xamarin.Behaviors;

In the same MyLibrary project, I am using d:ContentPageBase inherit from custom basepagewhich is working properly. But Behaviors not working.
Any help would be really appreciated. Thanks

StringFormat messing with values (Duel Binding)

$
0
0

I have the following line in my xaml code

The value in the database is 1000.00

  <Entry x:Name="EntryItemValue" Placeholder="Purchased Price" Text="{Binding ItemValue, StringFormat='{0:0.00}'}" HorizontalOptions="FillAndExpand"></Entry>

In the xamarin app (android) it displays 1000,00 which is fine because that's how the culture is set on my phone.
BUT when I click update in the app and I have a Breakpoint set in visual studio. Now all of the sudden ItemValue is 100000,00

I am not even using Convert.ToDecimal or any other conversions just a basic Breakpoint to view the value. and if I continue and click save again the value becomes 10000000,00

If I input 1000.00 and save it will display again 1000,00
My Phone is set on English (South Africa)

If I set my phone to English (US) the app works as expected.

How can I do the binding to display correctly but also do the conversion correctly no matter the phone's Language Settings

How to bind value as id and text as string of the list in Picker control in xamarin forms ?

$
0
0

=> Please check out below example for more understanding.
e.g.(1) var list = [{
"id": 1,
"name": "xyz" },{
"id": 2,
"name": "xyz1" }]
2) country dropdown list : India as text and 1 as value , US as Text and 2 as value.

I need to bind 2 properties in the picker while right now we add only picker.Items.Add(value) (not the other property in picker)

Please give me the solution.

Thanks

base class for pages, that includes xaml

$
0
0

Hey,

I am trying to write a base page for my pages, that include xaml (the idea is to have a base page for all pages that can display a loading symbol). So I do this:

BasePage.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="OM_App.Pages.BasePage">
  <ContentPage.Content>
    <AbsoluteLayout  HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
      <ContentView x:Name="SubContent" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1">
      </ContentView>
      <ActivityIndicator x:Name="actInd"
                         AbsoluteLayout.LayoutFlags="PositionProportional"
                         AbsoluteLayout.LayoutBounds="0.5,0.5,-1,-1">
    </AbsoluteLayout>
  </ContentPage.Content>

</ContentPage>

(Later a mechanism to hide an show the ActivityIndicator will be inserted, but that is not relevant here).

In the cs code I overwrite the "Content" property to redirect to the SubContent:

using Xamarin.Forms;

namespace OM_App.Pages
{
    public partial class BasePage : ContentPage
    {
        new View Content
        {
            get
            {
                return SubContent.Content;
            }
            set
            {
                SubContent.Content = value;
            }
        }

        public BasePage()
        {
            InitializeComponent();
        }
    }
}

Now I make a page based in this:

TestPage.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<l:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="OM_App.Pages.TestPage"
             xmlns:l="clr-namespace:OM_App.Pages;assembly=OM_App"
             Title="Test Page">
  <l:BasePage.Content>
    <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Orientation="Vertical" Spacing="15">
      <Label Text="Test"/>
  </l:BasePage.Content>
</l:BasePage>

TestPage.xaml.cs:

namespace OM_App.Pages
{
    public partial class TestPage: BasePage
    {
        public ConfigDataInputPage()
        {
            InitializeComponent();
        }
    }

}

It compiles, but the AcrivityIndicator is not shown.

Any Idea what I am doing wrong?


Will UI elements ever respond to device Accessibility font sizes?

Forms9Patch: Simplify multi-device image management in your PCL Xamarin.Forms mobile apps

$
0
0

Announcement of Form9Patch

Xamarin Forms is great for developing apps on Android and iOS but it is missing two important tools for developers: scalable images and PCL multi-screen image management. Android developers use NinePatch bitmaps and the drawable directory naming convention for this purpose. Likewise, iOS developers use ResizeableImageWithCapInsets and the @2x, @3x, @4x file naming convention for this purpose.

Forms 9 Patch enhances Xamarin Forms to enable multi-resolution / multi-screen image management to PCL apps for iOS and Android.

What is it?

Simply stated, Forms9Patch is two separate elements (Image and ImageSource) which are multi-screen / multi-resolution extensions of their Xamarin Forms counterparts.

Forms9Patch.ImageSource

Xamarin Forms provides native iOS and Android multi-screen image management (described here). This requires storing your iOS images using the native iOS schema and storing your Android images using the Android schema. In other words, duplicative efforts to get the same results on both Android and iOS. Forms9Patch.ImageSource extends Xamarin.Forms.ImageSource capabilities to bring multi-screen image management to your PCL assemblies - so you only have to generate and configure your app's image resources once. Forms9Patch.ImageSource is a cross-platform implementation to sourcing multi-screen images in Xamarin Forms PCL apps as embedded resources.

Forms9Patch.Image

Forms9Patch.Image compliments Xamarin.Forms.Image to provide Xamarin Forms with a scaleable image element. Scalable images are images that fill their parent view by stretching in designated regions. The source image for the Forms9Patch.Image element can be specified either as a Forms9Patch.ImageSource or a Xamarin.Forms.ImageSource. Supported file formats are NinePatch (.9.png), .png, .jpg, .jpeg, .gif, .bmp, and .bmpf.

Example code

After adding the file bubble.9.png to your PCL project assembly as an EmbeddedResource, you can display it using something like the following:

var bubbleImage = new Forms9Patch.Image () {
    Source = ImageSource.FromResource("MyDemoApp.Resources.bubble.9.png"),
    HeightRequest = 110,
}
var label = new label () {
    Text = "Forms9Path NinePatch Image",
    HorizontalOptions = LayoutOptions.Center,
}

Example XAML

In Xamarin Forms, access to embedded resources from XAML requires some additional work. Unfortunately, Forms9Patch is no different. As with Xamarin Forms, you will need (in the same assembly as your embedded resource images) a simple custom XAML markup extension to load images using their ResourceID.

    [ContentProperty ("Source")]
    public class ImageMultiResourceExtension : IMarkupExtension
    {
        public string Source { get; set; }

        public object ProvideValue (IServiceProvider serviceProvider)
        {
            if (Source == null)
                return null;

            // Do your translation lookup here, using whatever method you require
            var imageSource = Forms9Patch.ImageSource.FromMultiResource(Source);

            return imageSource;
        }
    }

Once you have the above, you can load your embedded resource images as shown in the below example. Be sure to add a namespace for the assembly that contains both your MarkupExtension and your EmbeddedResources (local in the below example).

<?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:MyXamlDemo;assembly=MyXamlDemo"
    x:Class="MyXamlDemo.MyPage"
    Padding="5, 20, 5, 5">
    <ScrollView>
        <ScrollView.Content>
            <StackLayout>
            <Label Text="Xamarin.Image"/>
            <Image Source="{local:ImageMultiResource Forms9PatchDemo.Resources.image}"/>
            </StackLayout>
        </ScrollView.Content>
    </ScrollView>
</ContentPage>

Where to learn more

Project page: http://Forms9Patch.com
Nuget page: https://www.nuget.org/packages/Forms9Patch/0.9.1
Demo app repository: https://github.com/baskren/Forms9PatchDemo

Implementation of google place autocomplete in xamarin forms project

$
0
0

Hi guys,
I have a project where i need to autocomplete an adress to be sure it's a valid one.
I've seen the sample of TK.CustomMap but i can't make it work (https://github.com/TorbenK/TK.CustomMap)

If someone have a sample where i could see a multiplatform use of this api it'll really help me.

PCL logging

$
0
0

Is there any PCL logger that logs everything into Device Log in Visual Studio?

I am refering to this blog post.

Android, Page.DisplayActionSheet, need more text room!

$
0
0

So I display an action sheet on iOS and Android in my app, giving the user various options for how to proceed. I use the Action Sheet because the choice is not binary, as an Alert would do. However, the message/title is a little longer than usual.

On iOS, the Action Sheet just expands to allow all the text to show.

On an Android phone, the text is simply truncated to two lines and given ellipses, with no apparent way to see the full text.

Is there a way to have the Android version show more of the text, or change the size of the text so more would fit in the allotted space?

Xamarin.Auth for UWP

$
0
0

I feel stupid for asking this but, I am new to Xamarin.Forms and have been trying to implement OAuth in my app. Now as far as I understand, Xamarin.Auth since 1.3.2 officially (finally) supports UWP, but I have no idea how to properly use the auth.GetUI method for UWP.

My attempts lead me to:

Frame rootFrame = Window.Current.Content as Frame;
rootFrame.Navigate(auth.GetUI(), null);

The last update to the GitHub page was in 2014 and has no information about UWP, and most Google results are about using WebAuthenticationBroker and not the Xamarin.Auth solution.

I believe it is a one or two line solution, I just have no idea what it is.

Carousel Page PagesChanged Event

$
0
0

Are there any events that fire when a CarouselPage is swiped (ie, the CurrentPage changes)?

I have a situation where a binding doesn't quite work, and would like to perform an operation when the page is changed.

i know that page.Appearing() gets fired all at once rather than when it seems to 'appear' to the user, so I was hoping the MultiPage event NotifyCollectionChangedEventHandler PagesChanged would be my answer but the documentation doesn't seem like it is exactly what I am looking for (and it doesn't appear to be firing or I am doing it wrong).

Thanks


Signature Pad View does not contain getImage

$
0
0

I have use the Xamarin Control SignaturePad Form in my PCL project. The code as below:

    public class DigitalSignature : ContentPage
     {
            SignaturePadView sign = new SignaturePadView();

            public DigitalSignature()
            {
                Button btnOk = new Button
                {
                    Text = "Ok",
                    BackgroundColor = Color.FromHex("#ff6600"),
                    HorizontalOptions = LayoutOptions.End,
                    WidthRequest = 100,
                    HeightRequest = 35,
                    FontSize = 15
                };

                btnOk.Clicked += btnOk_Clicked;

                sign = new SignaturePadView()
                {
                    SignatureLineColor = Color.Red,
                    StrokeColor = Color.Black,
                    StrokeWidth = 10f,
                    HeightRequest = 150,
                    BackgroundColor = Color.White,
                    ClearText = "Clear Me"
                };
                sign.CaptionText = "pls sign here";


                Content = new StackLayout
                {
                    Children = {
                        sign,
                        btnOk
                    }
                };

            }

            private void btnOk_Clicked(object sender, EventArgs e)
            {

            }
        }

How I can get the signature as image and store in the database? In the signaturepadview do not has the getImage() function. Anyone has idea how I can do that?

Thanks,
Derick

Touch and hold button to repeat action

$
0
0

Hi,

I have a requirement to develop a control similar to the Number Picker in Xamarin forms (where you have a + and - button to set a value). I need to show a + and - button and a label showing the current value. I need to be able to hold the button down to increment the number - not tap on the button over and over. I only really need it for Android.

I have created a custom control extending from View with a bindable property for CurrentValue. I have then created a custom renderer which returns a relative layout with two buttons and a label. I have called SetOnTouchListener and created a function to SetOnTouchListener which increments the number when either of the buttons are pressed. This all works fine when i press the button once -> the OnElementPropertyChanged event is fired and the UI updates. I have tried creating a timer on the ondown Motion and updating the "SelectedValue" of the control on an interval while the button remains down - but the OnElementPropertyChanged doesent fire in this case.

Is there something i am missing here? Below is what my OnTouchListener looks like. Is it because the timer cannot update the main thread? I put a breakpoint on my customControl binded property and i can see the setter for it is being called - but the value dosent change.

Please help!

public class MyTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener
{
CustomControl myCustomControl;
CustomControlRenderer myCustomControlRenderer;
Android.Widget.RelativeLayout myRelativeLayout;

        public static readonly MyTouchListener Instance = new MyTouchListener();

        private int _normalInterval;
        private int _initialInterval;
        private Timer _timer;
        private bool _isLongPress = false;

        public MyTouchListener()
        {
            _initialInterval = 500;
            _normalInterval = 1000;
            _timer = new Timer(_initialInterval);
            _timer.Enabled = false;
            _timer.Elapsed += HandleTimerElapsed;
        }

        void HandleTimerElapsed(object sender, ElapsedEventArgs e)
        {
            _isLongPress = true;
            InvokeClickListener();
            _timer.Interval = _normalInterval;
        }

        private void InvokeInitialClickListener()
        {
            myCustomControl.SelectedValue++;
        }

        private void InvokeClickListener()
        {
            myCustomControl.SelectedValue++;
        }

        private void InvokeCancelListener()
        {

        }

        public bool OnTouch(Android.Views.View v, Android.Views.MotionEvent e)
        {
            var renderer = v.Tag as CustomControlRenderer;
            if (renderer == null)
                return false;

            myRelativeLayout= renderer.Control;
            myCustomControl= renderer.Element;

            if (v == renderer._upButton)
                switch (e.Action)
                {
                    case MotionEventActions.Down:
                        _timer.Enabled = true;
                        _timer.Start();
                        _isLongPress = false;
                        InvokeInitialClickListener();
                        return true;
                    case MotionEventActions.Up:
                    case MotionEventActions.Cancel:
                        _timer.Stop();
                        InvokeCancelListener();
                        return true;
                }
            return false;
        }
    }

"Java.Lang.IllegalStateException: Activity has been destroyed" when using AdMob

$
0
0

I have done some tests of how to use AdMob in Xamarin.Forms and I got stuck on this.
Scenario:

  • A MasterDetailPage containing an empty master and a detail that is a new NavigationPage(myAdPage)
  • Start the application
  • Click on the (test)-ad and it will open a window
  • Click on the hardware back button twice and you get Java.Lang.IllegalStateException: Activity has been destroyed

A simple solution is attached.

Any clues of what to change to avoid this crash?

Objective-C exception: CALayerInvalidGeometry

$
0
0

I get this quite often since I work with the picker control (I load data asynchronously, assign it to the picker datasource and so on).

I get this in different cases, sometimes I the error occurs, sometimes not. Any Idea what the problem could be or did anybody have the same problems?

MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown.  Name: CALayerInvalidGeometry Reason: CALayer bounds contains NaN: [0 nan; 320 291]
  at at (wrapper managed-to-native) MonoTouch.ObjCRuntime.Messaging:void_objc_msgSend_int_int_bool (intptr,intptr,int,int,bool)
  at MonoTouch.UIKit.UIPickerView.Select (Int32 row, Int32 component, Boolean animated) [0x00010] in /Developer/MonoTouch/Source/monotouch/src/build/compat/UIKit/UIPickerView.g.cs:185
  at Xamarin.Forms.Platform.iOS.PickerRenderer.UpdatePicker () [0x00000] in <filename unknown>:0
  at Xamarin.Forms.Platform.iOS.PickerRenderer.OnModelSet (Xamarin.Forms.VisualElement model) [0x00000] in <filename unknown>:0
  at Xamarin.Forms.Platform.iOS.ViewRenderer.SetModel (Xamarin.Forms.VisualElement model) [0x00000] in <filename unknown>:0
  at Xamarin.Forms.Platform.iOS.RendererFactory.GetRenderer (Xamarin.Forms.VisualElement view) [0x00000] in <filename unknown>:0
  at Xamarin.Forms.Platform.iOS.ViewPackager.HandleChildAdded (Xamarin.Forms.VisualElement view) [0x00000] in <filename unknown>:0
  at Xamarin.Forms.EnumerableExtensions.ForEach[VisualElement] (IEnumerable`1 enumeration, System.Action`1 action) [0x00000] in <filename unknown>:0
  ....

Best method to hide and show views based on userlevel

$
0
0

Hi everyone, what is the appropriate way to hide and show views for instance using someones userlevel in MVVM?

I know that you can change the IsVisible BindableProperty and Bind it to something on the backend, but that seems quite messy. Is there a better way to deal with this?

Viewing all 89864 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>