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

XamlC compiles, but throws InvalidCastException: Specified cast is not valid in InitializeComponent

$
0
0

Hi,

Updated my XF project to 2.0.0.6487 and verified that it's still working. Then I enabled XamlC on the assembly level. Android project builds without issues but dies on my Android 4.3 device in the InitializeComponent() call of the first page.

System.InvalidCastException: Specified cast is not valid.

Stacktrace does not reveal any additional information. Any tips where I should start debugging?


'Plugin.Iconize.Fonts.FontAwesomeCollection' threw an exception

$
0
0

I'm trying to use the Xam.Pugin.Iconize.FontAwesome nuget package with my xamarin.forms shared app (targeting Android only). The app compiles fine, but when running the app, I get the following exception:

System.TypeInitializationException: The type initializer for 'Plugin.Iconize.Fonts.FontAwesomeCollection' threw an exception.

I have the following nugets installed (all are the latest versions):

Xam.FormsPlugin.Iconize 1.5.0.13-beta
Xam.Plugin.Iconize 2.0.0.37-beta
Xam.Pugin.Iconize.FontAwesome 2.0.0.37-beta

My version of xamarin.forms is 2.5.1527436, which is within the required version range required by Iconize (>= 2.3.5 && < 3.0.0).

As per the instructions on the Xam.FormsPlugin.Iconize web page, in my OnCreate(Bundle bundle) method in MainActivity.cs I have set as follows:

base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
Plugin.Iconize.Iconize.With(new Plugin.Iconize.Fonts.FontAwesomeModule());
FormsPlugin.Iconize.Droid.IconControls.Init(Resource.Id.toolbar, Resource.Id.tabs);

The only version of Xam.Pugin.Iconize.FontAwesome I can get working is the 1.5.0.13-beta release, but this has lots of icons missing from the current FontAwesome collection, so would like to get the latest package working. Alternatively is there an easier way to use FontAwesome in a xamarin.forms shared project?

How to customize rating bar size in xamarin forms

$
0
0

I used This XFControls plugin to create Rating bar in my app but This bar is too large in phones and i want to customize its size
I tried witdth request but it didn't work for me

xmlns:Rating="clr-namespace:AsNum.XFControls;assembly=AsNum.XFControls"

my xaml

     <Rating:RatingBar BackgroundColor="SeaGreen"

                                        StarCount="5" Step="0.5"  SelectedColor="Orange"
                                                       HeightRequest="40" HorizontalOptions="Fill" UnSelectedColor="LightGray" Rate="{Binding Rating,Mode=TwoWay}">

                                        </Rating:RatingBar>

how can i do that ?

Navigating from Android activity back to forms

$
0
0

I have forms project where I use a custom ContentPage and a PageRenderer based on this code:

forums.xamarin.com/discussion/18014/mixing-forms-content-and-native-activity

I can navigate to my android activity with :

buttonB.Clicked += async (object sender, EventArgs e) => await Navigation.PushAsync(new MapPage());

but I cant figure out how to navigate back to the forms page, the back button does not do anything.

MapPage is simply and empty ContentPage.

My Renderer looks like this:

`
using System;
using Xamarin.Forms.Platform.Android;
using Android.Gms.Maps;
using Xamarin.Forms;
using Android.App;
using Android.Views;
using Android.Gms.Maps.Model;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.ComponentModel;
using Android.Graphics;

[assembly:ExportRenderer(typeof(FormsMaps.MapPage), typeof(FormsMaps.Droid.MapPageRenderer))]
namespace FormsMaps.Droid
{
public class MapPageRenderer : PageRenderer
{
Android.Views.View view;
private MapFragment _mapFragment;
private GoogleMap _map;
private bool _gettingMap;
private MapPage _mapPage;

    private Activity _activity;

    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
    {
        base.OnElementChanged(e);

        _mapPage = (MapPage)e.NewElement;
        SetPage(_mapPage);
        // load the axml file for this view
        _activity= this.Context as Activity;
        _activity.SetContentView(Resource.Layout.MapLayout);

        view = _activity.LayoutInflater.Inflate(Resource.Layout.MapLayout, this, false);
        AddView(view);


        InitMapFragment();
        SetupMapIfNeeded(); // It's not gauranteed that the map will be available at this point.
    }

    private void InitMapFragment()
    {

        _mapFragment = _activity.FragmentManager.FindFragmentByTag("map") as MapFragment;
        if (_mapFragment == null)
        {
            GoogleMapOptions mapOptions = new GoogleMapOptions()
                .InvokeMapType(GoogleMap.MapTypeTerrain)
                .InvokeZoomControlsEnabled(true)
                .InvokeCompassEnabled(true)
                .InvokeRotateGesturesEnabled(true)
                .InvokeScrollGesturesEnabled(true)
                .InvokeTiltGesturesEnabled(true)
                .InvokeZoomGesturesEnabled(true);


            FragmentTransaction fragTx = _activity.FragmentManager.BeginTransaction();
            _mapFragment = MapFragment.NewInstance(mapOptions);
            fragTx.Add(Resource.Id.map, _mapFragment, "map");
            fragTx.Commit();
            Markers = new List<Marker>();
        }
    }



    private void SetupMapIfNeeded()
    {
        if(null != _map || _gettingMap) return;

        var mapReadyCallback = new MyOnMapReady();

        mapReadyCallback.MapReady += (sender, args) =>
        {
                _map = mapReadyCallback.Map;
                // set up annotations etc here

            _gettingMap = false;
        };

        _gettingMap = true;
        _mapFragment.GetMapAsync(mapReadyCallback); 

    }

}

}`

How can I navigate back?

Drag Drop support in Xamarin Forms

$
0
0

I am porting a rather rich UI from WinRT to Xamarin.Forms. I have searched the forums and have found that there is no real support for Drag and Drop.
In my app I have a grid (students in a class room), and a user can re-arrange seats by dragging any Grid Cell over an existing or empty cell and the letting go.
In WinRT I was able to use the ItemPointerMoved event to track the users touch point, and then the VisualTreeHelper to find controls under the pointer.
I can't find anything similar on Xamarin.

I am surprised that there is so little support in the Mobile world for a rich DragDrop api.
I was hoping to find something modelled after UWP, which provides a "CanDrag" property on the VisualElement and then fires DragStarting, DragEnter, DragOver, DropCompleted events. Support is almost automatic.

This is an elegant, powerful and simple to use architecture (not sure why it was not supported on WinRT)

There now seems to be similar support on Android and IOS (since IOS 11).

Here's hoping that it comes to Xamarin. Maybe via Xamarin Essentials.

Iphone device is not showing in debug list in project.

$
0
0

Hello,
I am creating an app for ios and android with help of xamarin.forms. When I am connecting my iphone device with my mac system for debugging the code it is not showing in the debug list. There is still showing Ios device. But if I open any other project of xamarin.forms Iphone option is showing in the debug list. I don't know why it is not showing only in one project. Is there any setting to enable the iphone device for project? Or any other way to manage iphone device with project?

How to open a file in a new window?

$
0
0

I'm using the code below in pcl to open a file stored locally:

Device.OpenUri(new Uri("file:///folder/file.pdf));

All is good and the file opens but when it opens it replaces my current page, ideally I would like to start an instance of the default app for pdf/jpg/txt/etc and leave my app as-is - is this possible?

Trouble with access to xaml-declared objects from code-behind file

$
0
0
After i've created a page design in xaml file, i tried to write some logic and buttons click actions, but when i was trying to access to any object in this page from code-behind file i got error "the object "...name" does not exist in this context"
I'm new, so maybe i dont know something or it's just some bug.

Xamarin cannot access disposed object error

$
0
0

i'm working with xamarin.forms, i'm trying to upload video content using MultipartFormDataContent with following code

 public async Task<bool> SaveNewsItemV1(EditNewsViewInputForMobile input)
        {
            try
            {

                NewsModels NewsInputModels = new NewsModels();
                NewsInputModels.NewsModel = input;

                //create new HttpClient and MultipartFormDataContent and add our file, and StudentId
                HttpClientHandler handler = new HttpClientHandler();

                using (var client = new System.Net.Http.HttpClient(handler, false))
                {
                    client.Timeout = new TimeSpan(0, 10, 0);

                    client.BaseAddress = new Uri(ServiceHelper.ServiceUrl);
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    string boundary = "---8d0f01e6b3b5dafaaadaad";
                    MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);
                    foreach (var item in SelectedMediaList) // obj of  List<Plugin.Media.Abstractions.MediaFile>
                    {
                        if (item != null && item.GetStream() != null)
                        {
                            Stream stream = item.GetStream();

                            byte[] imageData;
                            using (MemoryStream ms = new MemoryStream())
                            {
                                stream.CopyTo(ms);
                                imageData = ms.ToArray();
                            }

                            var baContent = new ByteArrayContent(imageData);

                            baContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
                            baContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                            {
                                Name = "file",
                                FileName = Path.GetFileName(item.Path)
                            };

                            multipartContent.Add(baContent);
                        }
                    }
                    try
                    {
                        var jData = JsonConvert.SerializeObject(NewsInputModels);
                        var content1 = new StringContent(jData, Encoding.UTF8, "application/json");
                        multipartContent.Add(content1, "Data"); // added input model data


                        var response = await client.PostAsync("SaveNewsItem/CommentNewsV1", multipartContent);

                        var result = response.Content.ReadAsStringAsync().Result;
                        var resultobject = JsonConvert.DeserializeObject<CommentResultData>(result);
                        return resultobject.Result;
                        return true;
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        return false;

                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return false;

            }
        }

in my case my HttpClient Throwing this error
Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream'.

Can anyone help with this??

how can i find distance between lat and long of maps?

$
0
0

how can i find distance between lat and long of maps? my code displaying polyline like this now i want to find distance between each coordinate..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
using CoreLocation;

namespace polyline
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MapPage : ContentPage
{
public MapPage()
{
InitializeComponent();
customMap.RouteCoordinates.Add(new Position(12.839939, 77.677003));
customMap.RouteCoordinates.Add(new Position(12.869582, 77.769525));
customMap.RouteCoordinates.Add(new Position(12.931541, 77.840302));
customMap.RouteCoordinates.Add(new Position(12.973947, 77.840302));
customMap.RouteCoordinates.Add(new Position(12.990840, 77.760781));
customMap.RouteCoordinates.Add(new Position(13.004017, 77.687776));
customMap.RouteCoordinates.Add(new Position(12.927923, 77.627108));
customMap.RouteCoordinates.Add(new Position(12.866189, 77.660413));

        var pin = new CustomPin
        {
          Type = PinType.Place,
            Position=new Position(12.839939, 77.677003),
            Label = "(Starting point)Electronic city",
            Address = "Electronic city,Banglore",
            Id = "1",

            //Url = "http://xamarin.com/about/"     
        };
        var pin1 = new CustomPin
        {
            Type = PinType.Place,
            Position = new Position(12.869582, 77.769525),
            Label = "Sompura",
            Address = "Sompura,Banglore",
            Id = "2",
           // Url = "http://xamarin.com/about/"
        };
        var pin2 = new CustomPin
        {
            Type = PinType.Place,
            Position = new Position(12.931541, 77.840302),
            Label = "kalkunte",
            Address = "kalkunte,Banglore",
            Id = "3",
            // Url = "http://xamarin.com/about/"
        };
        var pin3 = new CustomPin
        {
            Type = PinType.Place,
            Position = new Position(12.973947, 77.840302),
            Label = "Devanagonthi",
            Address = "Devanagonthi,Banglore",
            Id = "4",
            // Url = "http://xamarin.com/about/"
        };
        var pin4 = new CustomPin
        {
            Type = PinType.Place,
            Position = new Position(12.990840, 77.760781),
            Label = "Kadugodi",
            Address = "Kadugodi,Banglore",
            Id = "5",
            // Url = "http://xamarin.com/about/"
        };
        var pin5 = new CustomPin
        {
            Type = PinType.Place,
            Position = new Position(13.004017, 77.687776),
            Label = "krishnarajapuram",
            Address = "krishnarajapuram,Banglore",
            Id = "6",
            // Url = "http://xamarin.com/about/"
        };
        var pin6 = new CustomPin
        {
            Type = PinType.Place,
            Position = new Position(12.927923, 77.627108),
            Label = "Kormangala",
            Address = "Kormangala,Banglore",
            Id = "7",
            // Url = "http://xamarin.com/about/"
        };
        var pin7 = new CustomPin
        {
            Type = PinType.Place,
            Position = new Position(12.866189, 77.660413),
            Label = "(Ending point)beratana agrahara",
            Address = "beratana agrahara,Banglore",     
            Id = "7",
            // Url = "http://xamarin.com/about/"
        };

        //customMap.CustomPins = new List<CustomPin> { pin };
        customMap.Pins.Add(pin);
        customMap.Pins.Add(pin1);
        customMap.Pins.Add(pin2);
        customMap.Pins.Add(pin3);
        customMap.Pins.Add(pin4);
        customMap.Pins.Add(pin5);
        customMap.Pins.Add(pin6);
        customMap.Pins.Add(pin7);
        customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(12.912342, 77.752929), Distance.FromMiles(10.0)));
    }

}

}

Usage of page from PCL (.NET Standard) project Xamarin Native Forms project

$
0
0

Hi,

In regards to Xamarin Native Forms feature, is there to the the following. I will make an example for Android platform:
1. Use pages from PCL (.NET Standard) project from Xamarin Native Forms Android project
2. In the MainActivity, can we call LoadApplication(new App()) like in Xamarin.Forms
3. Later on, from some page in PCL (.NET Standard) project on button click, can we open page defined in Native Forms Android Project?

Regards,
Novak

Hybrid navigation

$
0
0

Hello,

I like Xamarin Forms but I have one doubt.
I need to have a splash carousel page that displays 3 carousel pictures at the top and sign in / login text fields and buttons at the bottom.
This page (after login), should lead to a page that has a drawer menu on the top left and options menu on the top right (typically Android), and some icons in the middle of the screen. Each icon will open a new activity, which will be hierarchical navigation, using a "next" button at the bottom of the page to move on with the navigation, but I would still need the menus at the top to be accessible from each page after the login.
Is it possible to achieve this with Forms? If yes, are there some examples around?
Till today I have always found examples that never mixed different kinds of navigation.

Thanks!
Max

Add NuGet Packages is disabled

$
0
0

Hi

I created a new .Forms solution.
The Add NuGet Packages... menu is disabled for the cross-platform folder.
The same menu is enabled for .iOS and .Droid and in other solutions.

Everything is up to date with the Xamarin environment.

Please, help me find the cause and solution.

Thanks
Steve

Flicker/delay happens while navigating to some other page on click of menu item in MasterDetail Page

$
0
0

Hi all,
I am using a Master detail Page in my xamarin forms project and its having a few items in slide out menu which opens some other page on their click event.
I am using the same approch which is given in xmarin site like :

public void PopulateSildeOutMenu()
{
string path = Helpers.Settings.getSettings ("ProfileImage");
if (String.IsNullOrEmpty (path)) {
path = "default.jpg";
}

        cand_dashboard_slideOutMenu_profileImage.FileSource = path;

        var slideOutMenuItems1 = new List<SlideOutMenuItem> ();
        slideOutMenuItems1.Add (new SlideOutMenuItem {
            Title = "Dashboard",
            IconSource = "dashboard.png",
            TargetType = typeof(DashboardHome)
        });
        slideOutMenuItems1.Add (new SlideOutMenuItem {
            Title = "Notifications",
            IconSource = "notifications.png",
            TargetType = typeof(DashboardHome)
        });
        slideOutMenuItems1.Add (new SlideOutMenuItem {
            Title = "My Profile",
            IconSource = "my_profile.png",
            TargetType = typeof(Profile)
        });

}

above code is in my slideout page and following in Masterdetail Page :

public partial class MasterDetail : MasterDetailPage
{

    public MasterDetail()
    {
        InitializeComponent ();
        NavigationPage.SetHasNavigationBar (this, false);
        slideOutMenu.ItemList1.ItemSelected += OnItemSelected;

    }


    async void OnItemSelected (object sender, SelectedItemChangedEventArgs e)
    {
        var item = e.SelectedItem as SlideOutMenuItem;
        if (item != null) {

                    Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
                    slideOutMenu.ItemList1.SelectedItem = null;
            IsPresented = false;
        }
    }
}

The above code works fine for me when I am navigating to other page in iOS but, same code creats a flicker/delay in opening next page while using in Android i.e. Page doesn't loads instantly. Any solution for that.. ?
Please suggest something, Thanks.

Setting MainPage = NavigationPage during OnStart in Xamarin.Forms display a blank screen in Android

$
0
0

I have a Xamarin Forms Application where I'm setting the MainPage to NavigationPage during OnStart.
The NavigationPage is static (kept in memory for reuse).
When I press the back button in Android and go back to the app the OnStart method is executed again and the application displays a blank screen.
The repro: OnStart Static NavigationPage

public partial class App : Application
{
    private static readonly NavigationPage NavigationPage = new NavigationPage(new MainPage());
    public App ()
    {
        InitializeComponent();
    }

    protected override void OnStart()
    {
        MainPage = NavigationPage;
    }
}

If I do the same action in the constructor the application behaves as expected: there's no blank screen and the last page visited is displayed.
The repro: Constructor Static NavigationPage

public partial class App : Application
{
    private static readonly NavigationPage NavigationPage = new NavigationPage(new MainPage());
    public App ()
    {
        InitializeComponent();

        MainPage = NavigationPage;
    }
}

What is the difference between setting the MainPage in the constructor and in the OnStart method?


Potential Proposal: Animation of MainPage Transition

$
0
0

I wanted to discuss this here before submitting a proposal because its a feature I would really like, page transitions, similar to those on a navigation page. But its far from simple to implement and I don't have a solid plan for an API as yet.

I can animate the transition of a MainPage with the following code changes in the Xamarin Forms source code.

iOS

In FormsAppDelegate.cs change this function

  void UpdateMainPage()
  {
       if (_application.MainPage == null)
            return;

        var platformRenderer = (PlatformRenderer)_window.RootViewController;

        if (platformRenderer != null)
            ((IDisposable)platformRenderer.Platform).Dispose();
        if (_window.RootViewController == null)
            _window.RootViewController = _application.MainPage.CreateViewController();
        else
            UIView.Transition(_window.RootViewController.View, 1, UIViewAnimationOptions.TransitionFlipFromBottom, () => { _window.RootViewController = _application.MainPage.CreateViewController(); }, () => { });

    }

Android
Android proves the hardest because I can only seem to transition in, once the previous page is removed. In Platform.cs I replace the following function:

  void AddChild(Page page, bool layout = false)
  {
       if (Android.Platform.GetRenderer(page) != null)
            return;

        Android.Platform.SetPageContext(page, _context);
        IVisualElementRenderer renderView = Android.Platform.CreateRenderer(page);
        Android.Platform.SetRenderer(page, renderView);

        if (layout)
            LayoutRootPage((FormsAppCompatActivity)_context, page, _renderer.Width, _renderer.Height);

        renderView.ViewGroup.StartAnimation(global::Android.Views.Animations.AnimationUtils.LoadAnimation(_context, global::Android.Resource.Animation.SlideInLeft));

        _renderer.AddView(renderView.ViewGroup);
      }

UWP
In UWP we add in this to the SetCurrent method in Platform.cs, just before the Children.Add line.

    if (_container.ChildrenTransitions == null)
    {
        _container.ChildrenTransitions = new TransitionCollection();
        _container.ChildrenTransitions.Add(new EntranceThemeTransition());
    }

The problem is, what API would be good to change the MainPage with an animation, we would need different platform specific code, but it would need to be called through a PCL, hence it would have to be an abstraction of some kind.

Next if anyone is up for the challenge, that Android page transition code needs a looking at.

Is it possible to define height and width in percentage in Xamarin forms?

$
0
0

How we can define height and width in percentage in Xamarin forms so that it can support different screens?

Listview selectedItem using MVVM and XAML

$
0
0

I am so frustrated that I cannot find one single WORKING example of how to get the selected item from a listview using XAML and MVVM. I have found numerous incomplete examples using different behaviors. I did find one promising one using Xamarin.Forms.Behaviors but again, couldn't get it to work. I'm new to Xamarin but I have been coding for 15 years and I have to say the learning curve here has be brutal.

I would really appreciate any help!

Font Awesome not working in iOS

$
0
0

Hello Guys,

I am using font awesome for fonts in application.
These fonts are working fine on ios emulator,
But when I create .ipa file and install that on iPhone then those fonts are not working.
Except the font it shows "?" images.

I added "fontawesome.ttf" in resource folder.
Also edited "Info.plist" file.

Plz help me out.

Font Awesome Problem

$
0
0

hello i have a weird problem
i am using font awesome in my xamarin forms app
it is working fine in my android emulator but when i try to run it on iphone emulator
it shows question marks instead of the font!
does anyone know how to solve this problem
this is how it looks like

Thanks in advance :smile:

Viewing all 91519 articles
Browse latest View live


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