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

finding an element on the current page?

$
0
0

I'm just trying to locate a named item (in this case it is an "entry" so that I can modify it) within the user's current-page. FWIW, for clarity I named the stackLayout it is contained in as well.

I used this code to track down the page (seems overtly cumbersome..but ok):
actionPage = Application.Current.MainPage;
if (actionPage.Navigation != null)
actionPage = actionPage.Navigation.NavigationStack.FirstOrDefault(); // .NavigationStack.Last();

I get null for the 'actionPage'.
Now, I'm noticing that the current page for the user in some cases is a "tabbed page". Maybe I need to trace through those in those cases as well, but again this is quite a bit of code to do something that seems extremely simple.

I'm going through the xamarin course, so I'm sure I'll get more help there but need to solve this issue very soon. Please help me.


This async method lacks 'await' operators and will run asynchronously

$
0
0
    Cant figure out how to get rid of the warning, any help appreciated.

ICommand refreshCommand;

    public ICommand RefreshCommand
    {
        get { return refreshCommand ?? (refreshCommand = new Command(async () => await ExecuteRefreshCommand())); }
    }

    public async Task ExecuteRefreshCommand()
    {
        if (IsBusy)
            return;

        IsBusy = true;

        // Refresh to this web page
        webView.Source = "https://www.google.com";

        webView.Navigated += (s, e) =>
        {
            IsBusy = false;
        };
    }

Upgrading packages, PCLs to .NET Standard, and my version of Xamarin Forms - best way to do this?

$
0
0

A bit of background on myself. I am an experienced Xamarin developer (largely native, but my knowledge coupled with understanding WPF has made Xamarin Forms pretty straightforward so far).

As for my the main reason for my post. I have a very large project (solution?) made up of many PCLs. The projects all use Xamarin Forms 2.4.0.74863. And the packages that the project depends on, including Telerik for some UI components, are all fairly outdated now. I've already noticed I'm having to make a lot of smelly hacks just to get some aspects of Xamarin Forms to work. But above all, I've read that leaving projects as PCLs is a very bad idea.

My first thought was to upgrade Xamarin Forms on my projects. This doesn't work straight to XF 3. I have managed to upgrade to 2.5.1.527436, but even doing this required upgrading my Visual Studio from 15.6.7 to 15.7.2. I plan to check in these changes after some thorough testing, as they're the only way I'm even able to use VS 15.7.2. (So I have a circular sort of issue, in a sense).

So, I think, my question is this:** How do I, instead of introducing a massive set of changes in my project, instead implement slightly less massive changes, by handling these things 1 at a time. That is, what order should I prioritise these tasks**?

My gut feeling is that I first need to upgrade to .NET Standard so that I can be done with PCL, above all else. In a previous job, 2 years ago when .NET Standard just became available, this wasn't even possible as there still wasn't a lot of support for .NET Standard. My hope is that this has hopefully come a long way since then. I plan to use this guide https://xamarinhelp.com/upgrade-pcl-net-standard-class-library/. But how can I really be sure that everything works? Keep in mind I have nearly 20 projects to upgrade.

From there, I would then take care of upgrading to Xamarin Forms 3 (whatever the latest stable version is) and then upgrade my packages to their latest stable versions.

Are there any pitfalls to the approach I've mentioned? I'm the only developer in my Xamarin team, so I'm trying to be quite cautious with this upgrade. And already, I've been through a lot of headaches of trying to get Xamarin Forms upgraded. So I'm a little paranoid.

I'd really appreciate any guidance/war stories on this.

validation part

$
0
0

I dont Know how to set the border color . if the user enter the wrong keyword then the border shows red color on it. let me know if anyone have this solution for this. I have attached sample image here. Thanks!

i need exactly same like this.

Task is getting locked while retreiving data in viewmodel

$
0
0

Hi my fellow developers.
I have been working on a app for a couple of months now but recently when
we started our testing phase i've been noticing some strange task lockups when loading
and transforming my data.

This is my viewmodel:

`
namespace Doshi.Dojo.ViewModels
{
public class AdviceViewModel : ViewModelBase
{
private NotifyTaskCompletion<ObservableCollection> _advisors;
public NotifyTaskCompletion<ObservableCollection> Advisors
{
get => _advisors;
set
{
SetProperty(ref _advisors, value);
}
}

    private readonly IContactsService _contactsService;
    private readonly IAdvisorService _adviserService;
    private readonly ITipService _tipService;
    private IUserService _userService;
    private IStatusService _statusService;

    public AdviceViewModel(INavigationService navigationService, IContactsService contactsService,
        IAdvisorService adviserService, ITipService tipService,
        IUserService userService, IUserDialogs userDialogs,
        IStatusService statusService) : base(navigationService)
    {
        _contactsService = contactsService;
        _adviserService = adviserService;
        _tipService = tipService;
        _userService = userService;
        _statusService = statusService;

        Advisors = new NotifyTaskCompletion<ObservableCollection<AdvisorModel>>(LoadAdvisorsAsync());
    }

    private async Task<ObservableCollection<AdvisorModel>> LoadAdvisorsAsync()
    {
        var contact_ids = await _contactsService.GetContactsIdsAsync();

        var advisorTasks = contact_ids.Select(i => CreateAdvisorModelAsync(i));
        var advisors = await Task.WhenAll(advisorTasks);

        var tipTasks = advisors.Select(a => FetchTipsAsync(a));
        advisors = await Task.WhenAll(tipTasks);

//STOPS HERE

        return new ObservableCollection<AdvisorModel>(advisors.ToList());
    }

    private async Task<AdvisorModel> CreateAdvisorModelAsync(string id)
    {
        var advisor_profile = await _adviserService.GetAdviserProfileAsync(id).ConfigureAwait(false);

        return new AdvisorModel
        {
            Website = advisor_profile.Website,
            ContactNumber = advisor_profile.ContactNumber,
            ID = advisor_profile.ID,
            ImageUrl = advisor_profile.ImageUrl,
            NameOfBusiness = advisor_profile.NameOfBusiness,
            StarRating = (int)advisor_profile.StarRating
        };
    }

    private async Task<AdvisorModel> FetchTipsAsync(AdvisorModel a)
    {
        var tips = await _tipService.GetTipsAsync(a.ID);

//CODE RUNS FINE TO HERE 

        var models = tips.Select(t => (TipModel)t);

        a.Tips = models.ToList();

//IF I LEAVE THIS BLOCK UNCOMMENTED 
//EXECUTION HALTS AT THE Task.WhenAll()

        return a;
    }
}

}
`

TipModel:

`
using Doshi.ApiCore.DTOs;
using Doshi.Core;
using System;

namespace Doshi.Core.Models
{
public class TipModel
{
public string Content { get; set; }
public string ID { get; set; }
public string OwnerID { get; set; }
public DateTime PublishDate { get; set; }
public bool Published { get; set; }
public string Title { get; set; }
public string Thumbnail { get; set; }

    public int Views { get; set; }

    public int Likes { get; set; }

    public int Dislikes { get; set; }

    public static explicit operator TipModel(TipDto tip)
    {
        var model = new TipModel
        {
            Content = tip.Content,
            ID = tip.ID,
            OwnerID = tip.OwnerID,
            PublishDate = tip.PublishDate,
            Published = tip.Published,
            Thumbnail = tip.Thumbnail,
            Title = tip.Title,
            Views = tip.Views
        };

        return model;
    }
}

}`

Any ideas what could be causing this.
Cheers!

File picker with multiple file selection

Listview - footer at the bottom right corner

$
0
0

I want to have a footer below Listview which is placed at the bottom right corner when there is not too much items in the listview. Here is my code:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Todo"
             x:Class="Todo.Views.TodoItems"
             xmlns:viewModels="clr-namespace:Todo.ViewModels"
             xmlns:controls="clr-namespace:Todo.Controls;"
             xmlns:suaveControls="clr-namespace:SuaveControls.Views;assembly=SuaveControls.FloatingActionButton"
             Title="Things to do!">
    <ContentPage.BindingContext>
        <viewModels:TodoItemsViewModel />
    </ContentPage.BindingContext>
    <StackLayout VerticalOptions="FillAndExpand">
        <ListView VerticalOptions="FillAndExpand" x:Name="listView" Margin="20,20,20,0" ItemsSource="{Binding TodoItems}" HasUnevenRows="True" SeparatorVisibility="None">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame Padding="5" Margin="7" HasShadow="True" MinimumHeightRequest="80">
                            <Grid VerticalOptions="Center" HorizontalOptions="Center">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="2.5*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="1.5*"/>
                                </Grid.ColumnDefinitions>
                                <Label Grid.Column="0" Text="{Binding Name}" VerticalTextAlignment="Center" HorizontalTextAlignment="Start" Margin="25,0,0,0" />
                                <Switch Grid.Column="1" IsToggled="{Binding Done}" HorizontalOptions="Start"/>
                            </Grid>
                        </Frame>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.Footer>
                <Label Text="lalalala" VerticalOptions="EndAndExpand" HorizontalOptions="End"/>
            </ListView.Footer>
        </ListView>
    </StackLayout>
</ContentPage>

It is not working even if I use FillAndExpand. I was searching on the Internet looking for the solution. Is there any way to achieve that footer at the bottom right corner when there is not too much items in the listview?

Application resources

$
0
0

Hi guys,
I have a question about Application Resources. I should change the style of my application. I tried to follow the instruction on https://developer.xamarin.com/guides/xamarin-forms/xaml/resource-dictionaries/ but nothing changed in my application.

I removed App.cs and I created a new ContentPage and I changed it like that:

App.xaml

<?xml version="1.0" encoding="UTF-8"?>
<Application xmlns="http://xamarin.com/schemas/2014/forms" 
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
     xmlns:theme="clr-namespace:Xamarin.Forms.Themes;assembly=Xamarin.Forms.Theme.Light" 
     x:Class="myInventories.App">
    <Application.Resources>
    <ResourceDictionary>
        <Color x:Key="PageBackgroundColor">Yellow</Color>
        <Color x:Key="HeadingTextColor">Black</Color>
        <Color x:Key="NormalTextColor">Blue</Color>
        <Style x:Key="LabelPageHeadingStyle" TargetType="Label">
            <Setter Property="FontAttributes" Value="Bold" />
            <Setter Property="HorizontalOptions" Value="Center" />
            <Setter Property="TextColor" Value="{StaticResource HeadingTextColor}" />
        </Style>
        <Style TargetType="Entry">
            <Setter Property="HorizontalOptions" Value="Fill" />
            <Setter Property="VerticalOptions" Value="CenterAndExpand" />
            <Setter Property="BackgroundColor" Value="Yellow" />
            <Setter Property="FontAttributes" Value="Italic" />
            <Setter Property="TextColor" Value="Blue" />
        </Style>
    </ResourceDictionary>
    </Application.Resources>
</Application>

App.xaml.cs

public partial class App : Application
{
    public App()
    {
        MainPage = new StartPage();
    }

    public static Page GetMainPage()
    {
        return new RootPage();
    }

    protected override void OnStart()
    {
        // Handle when your app starts
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
    }
}

I was expecting the background application Yellow. What is wrong? Thank you in advance.


XAML resources: create color based on another color in the dictionary?

$
0
0

Let's say I have a ResourceDictionary with a color defined:

<Color x:Key="MyColor">#000</Color>

I need to create another color based on that color, with the alpha channel adjusted. I've tried creating a markup extension and using it like this:

<Color x:Key="MyOtherColor" x:FactoryMethod="FromHex" x:Arguments="{core:ModifyColor Other={StaticResource MyColor} Alpha=0.5 }" />

The extension returns the new color as a hex string.

However, it seems like the parser isn't getting the value from my extension before calling FromHex and I get the following error:

No static method found for Xamarin.Forms.Color::FromHex (Core.ModifyColorExtension)

I've been banging my head on the wall for hours now trying to figure this out.

I feel like there's gotta be an easy way to do this... am I wrong?

The application is in break mode - "Specified cast is not valid"

$
0
0

When developing in Xamarin Forms if I will make a mistake in XAML syntax, I receive an error like this: "The application is in break mode. Unhandled exception: Specified cast is not valid"

Here is an example how to produce such an error:

<?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="Test.Views.ItemsPage"
              Title="{Binding Title}"
             x:Name="BrowseItemsPage">
    <ContentPage.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <ListView Parent="0,30,0,0" Grid.Row="0" x:Name="ItemsListView" 
                ItemsSource="{Binding Items}"
                VerticalOptions="FillAndExpand"
                 HasUnevenRows="true">
                <ListView.Header>
                    <Label Text="Unread messages: 3"/>
                </ListView.Header>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <!--<ViewCell>-->
                            <StackLayout Padding="10">
                                <Label Text="{Binding Text}" 
                       LineBreakMode="NoWrap" 
                       Style="{DynamicResource ListItemTextStyle}" 
                       FontSize="16" />
                                <Label Text="{Binding Description}" 
                       LineBreakMode="NoWrap"
                       Style="{DynamicResource ListItemDetailTextStyle}"
                       FontSize="13" />
                            </StackLayout>
                        <!--</ViewCell>-->
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </ContentPage.Content>
</ContentPage>

As you can I have just commented out ViewCell tags. In practice this error happens very often when you will break sth in XAML syntax and the exception tells completely nothing. Is there a way catch this exception and see details. Because when I have some complicated XAML it takes some time to detect which change in code produced that exception. I would be grateful for any help :smile:

MVVM .NET Standard hamburger menu sample

$
0
0

Hello

Can someone please provide me with a full working example of a hamburger menu using .NET standard and MVVM pattern?

When creating a new Xamarin project in Visual Studio 2017 (15.6.2) there is the option to use a Master Detail template, however it unfortunately uses a tabbed page layout instead of a hamburger menu.

There is a Microsoft site that explains how to use a Master-Detail page "MasterDetailPageNavigation", unfortunately it is a PCL project, which is now deprecated/obsoleted. In addition the project's structure seems quite odd.
The Microsoft article explaining Master-Detail pages:
docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/master-detail-page
The download link of the project:
developer.xamarin.com/samples/xamarin-forms/Navigation/MasterDetailPage
(sorry, I am not yet allowed to post links...)

The ideal solution would look like a merge between the Visual Studio "Master Detail" template and the "MasterDetailPageNavigation" solution.
This new solution would use .NET standard, MVVM pattern and of course a hamburger menu.

On a side note:
Does anyone know why the Master Detail template in Visual Studio uses a tabbed page instead of a hamburger menu?
There seem to be a lot of apps using a hamburger menu but the ones with a tabbed view are not that common, thus it seems quite odd to chose a tabbed page intead of a hamburger menu...

Any help is much appreciated.

Kind regads

Cannot find a resource of the Android version

$
0
0

I have a Xamarin.Forms application that is deployed on both iOS and Android.
In the latest version, I'm having an issue that the build (from AppCenter) is crashing with the following message:

(wrapper dynamic-method) System.Object.1060f582-4695-4003-9852-3f5a0d375371(intptr,intptr,intptr,intptr,intptr)
android.content.res.Resources$NotFoundException: Resource ID #0x7f0b0071
android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:215)

I searched for the resource with the ID #0x7f0b0071 and found the following:

// aapt resource value: 0x7f0b0071
public const int abc_tint_switch_track = 2131427441;

I'm not sure exactly what abc_tint_switch_track is. This file is auto-generated but I don't know why it has added this value or where it is used.

What is happening here?

URL to open the app, if installed?

$
0
0

I have a web app, and when someone inserts a new order, some users have chosen to receive a link to that new order (example: www.myulr/orders/34).

Now I also have a Xamarin Forms app (it's a webview that just loads the website for now).

When they click on the link from a phone, is it possible to open the app, if they have it installed?

If it is, how can I do that?
Ideally it would recognize that they have the app installed, and it would launch it and automatically point the webview to that url.

I heard about deep-linking but i can't figure out how to make it work (and if it is the right solution).
Any code snipped would be greatly helpful!

Thanks in advance!

How to implement document picker in ios?

$
0
0

I need to implement document picker in ios, im using visual studio 2017 and netstandard code strategy.
I'm using plugins and not works, always returns error "this functionality is not implemented ...." and
others dont do anything.
I've had too time in this and I have not found a response.
Im have the AppId, and the provisioning profile with the capabilities with Cloudkit, im have the configurations and the Entitlements.plist, Im have one interface to try to implement this, but in this part is on the i'm are in trouble, im never programming in objective c. Im have the archives in icloud in the iphone, i need to can select the archive and validate the extension.
Thanks in advance.

Very first OnAppearing animations doesn't work

$
0
0
The issue is reproduced both on Android and iOS.

The application's first content page has animations in the OnAppearing method.

When I start the application, it seems like the page's OnAppearing method is being called in parallel with the Splash screen or something. Anyway, it results with no animations in the first appearing.

Then, navigating to another page and back shows the animations great.

Any idea or advice with this subject? Thanks!

Displaying a UIDocumentMenuViewController

$
0
0

I'm trying to display a UIDocumentMenuViewController from the view model in a Xamarin.Forms application. The UIDocumentMenuViewController displays correctly, but when I select a provider the UIDocumentPickerViewController displays a black screen. The view hierarchy looks the same as for the Xamarin DocPicker sample. Am I using the right view controller here?

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

using UIKit;
using Foundation;
using MobileCoreServices;

using Oban.Mobile.Services;

namespace Oban.Mobile.iOS.Services
{
    public class FilePicker : IFilePicker
    {
        public async Task<ImportedFile> ImportFile(List<string> contentTypes)
        {
            var ubiq = await Task.Run(() => NSFileManager.DefaultManager.GetUrlForUbiquityContainer(null));
            if (ubiq == null)
            {
                throw new Exception("iCloud not available");
            }

            TaskCompletionSource<ImportedFile> tcs = new TaskCompletionSource<ImportedFile>();

            var allowedUTIs = new string[] { UTType.UTF8PlainText,
                    UTType.PlainText,
                    UTType.RTF,
                    UTType.PNG,
                    UTType.Text,
                    UTType.PDF,
                    UTType.Image };

            var activeController = UIControllerHelper.FindActiveViewController();

            UIDocumentMenuViewController pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Import);
            pickerMenu.WasCancelled += (sender, args) => tcs.SetResult(null);
            pickerMenu.DidPickDocumentPicker += (sender, args) =>
            {
                args.DocumentPicker.WasCancelled += (docSender, docArgs) => tcs.SetResult(null);
                args.DocumentPicker.DidPickDocument += (docSender, docArgs) =>
                {
                   ImportedFile file = null;

                    try
                    {
                        var securityEnabled = docArgs.Url.StartAccessingSecurityScopedResource();
                        var data = NSData.FromUrl(docArgs.Url); 

                        file = new ImportedFile(docArgs.Url.LastPathComponent, data.ToArray());
                        tcs.SetResult(file);
                    }
                    catch (Exception excp)
                    {
                        tcs.SetException(excp);
                    }
                    finally
                    {
                        docArgs.Url.StopAccessingSecurityScopedResource();
                    }

                };

                args.DocumentPicker.View.TranslatesAutoresizingMaskIntoConstraints = false;
                args.DocumentPicker.View.BackgroundColor = UIColor.White;

                args.DocumentPicker.ModalPresentationStyle = UIModalPresentationStyle.FullScreen;
                args.DocumentPicker.View.Frame = activeController.View.Frame;
                args.DocumentPicker.View.Bounds = activeController.View.Bounds;
                activeController.PresentViewController(args.DocumentPicker, true, null);
            };


            pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover;
            pickerMenu.View.TranslatesAutoresizingMaskIntoConstraints = false;
            activeController.PresentViewController(pickerMenu, true, null);

            UIPopoverPresentationController presentationPopover = pickerMenu.PopoverPresentationController;
            if (presentationPopover != null)
            {
                presentationPopover.SourceView = activeController.View;
                presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down;
                presentationPopover.SourceRect = activeController.View.Frame;
            }

            return await tcs.Task;
        }
    }

    public static class UIControllerHelper
    {
        public static UIViewController FindActiveViewController()
        {
            UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (vc.PresentedViewController != null)
            {
                vc = vc.PresentedViewController;
            }
            return vc;
        }

     }

    public class ImportedFile
    {
        public string FileName { get; private set; }

        public byte[] Content { get; private set; }

        public ImportedFile(string fileName, byte[] content)
        {
            this.FileName = fileName;
            this.Content = content;
        }
    }

    public interface IFilePicker
    {
        Task<ImportedFile> ImportFile(List<string> contentTypes);
    }
}

Fake Compile Errors

$
0
0

I have a project that compiles normally. Xamarin forms, IOS.
If I put a compile error in any file (like the one below), it reports numerous "fake" errors (69 of them). I see many like "The name 'Initialze component' does not exist in the current context". There are so many of these that it is difficult to find the real error. Is there a way to suppress these fake errors? I assume it has something to do with a first pass compile error or something like that.

strxng x = "";

Is Random working?

$
0
0

Hello!
I wanted to add to my C# file in Xamarin.Forms this part

Random rnd = new Random(); int Number = rnd.Next(1, 3);

However Visual Studio keeps telling that there is no definition Next in Random, this is the first time I see this issue; Console Apps have the same code and there's no problem with them.
P.S. I use System.Collections.Generic

How to make a custom Frame

$
0
0

So, I'm working on an app to show information about city locations and I wanted to use something similar to the Frame that is possible in Xamarin.

I was looking for something like this is attached

But I have not found any documentation on how to extend the Frame class, I tried creating a public class and inheriting from Frame but to no avail.

And I want to do this programatically (In C#, not xaml)

Get parent class from DataTemplate

$
0
0

Hi there, i come from a Unity C# background but Xamarin is a bit different regarding Data and Bindings and i have some doubts regarding how to do it.

Description of my problem
Is there any way to obtain the class that is being renderer by a DataTemplate, inside a DataTemplate?, If i'm doing wrong, can you suggest a better way to do this?

PseudoExample of what i'm trying to accomplish

Structure
MyClass.cs
MyClassDataTemplate.cs

Code
public DataTemplate MyClassDataTemplate()
{
return new DataTemplate(() =>
{
MyClass class = this.MyClass.Foo;
return new ViewCell();
}
}

Link i found quite related to this
https: // forums.xamarin.com/discussion/71462/datatemplate-with-templateselector-bind-to-parent-command

Additional Comments
I use pure C# with Xamarin.Forms, i searched a lot of questions and things but a lot are in XAML and i can't find the right answer to be honest.

Thank you in advanced!

Viewing all 89864 articles
Browse latest View live


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