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

Shell bottom Navigation How to implent to shell renderer for android and ios?

$
0
0

//BottomTabbedPageExtensions.cs

using Xamarin.Forms;

namespace SchedulingTool.Helpers
{
public class BottomTabbedPageExtensions
{
public static readonly BindableProperty TabColorProperty = BindableProperty.CreateAttached(
"TabColor",
typeof(Color),
typeof(BottomTabbedPageExtensions),
Color.Transparent);

    public static readonly BindableProperty BadgeCountProperty = BindableProperty.CreateAttached(
        "BadgeCount",
        typeof(int),
        typeof(BottomTabbedPageExtensions),
        0);

    public static readonly BindableProperty BadgeColorProperty = BindableProperty.CreateAttached(
        "BadgeColor",
        typeof(Color),
        typeof(BottomTabbedPageExtensions),
        Colors.OrangeColor);

    public static readonly BindableProperty IsTabVisibleProperty = BindableProperty.CreateAttached(
        "IsTabVisible", typeof(bool), typeof(BottomTabbedPageExtensions), true);

    public static void SetIsTabVisible(BindableObject bindable, bool visible)
    {
        bindable.SetValue(IsTabVisibleProperty, visible);
    }

    public static bool GetIsTabVisible(BindableObject bindable)
    {
        return (bool)bindable.GetValue(IsTabVisibleProperty);
    }

    public static void SetTabColor(BindableObject bindable, Color color)
    {
        bindable.SetValue(TabColorProperty, color);
    }

    public static Color GetTabColor(BindableObject bindable)
    {
        return (Color)bindable.GetValue(TabColorProperty);
    }

    public static void SetBadgeCount(BindableObject bindable, int badgeCount)
    {
        bindable.SetValue(BadgeCountProperty, badgeCount);
    }

    public static int GetBadgeCount(BindableObject bindable)
    {
        return (int)bindable.GetValue(BadgeCountProperty);
    }

    public static void IncreaseBadgeCountBy(BindableObject bindable, int increaseBy)
    {
        int currentValue = GetBadgeCount(bindable);
        if(currentValue == 0 && increaseBy < 0)
        {
            bindable.SetValue(BadgeCountProperty, 0);
        }

        if(increaseBy < 0 && (increaseBy > currentValue))
        {
            bindable.SetValue(BadgeCountProperty, 0);
        }

        bindable.SetValue(BadgeCountProperty, currentValue + increaseBy);
    }

    public static void SetBadgeColor(BindableObject bindable, Color color)
    {
        bindable.SetValue(BadgeColorProperty, color);
    }

    public static Color GetBadgeColor(BindableObject bindable)
    {
        return (Color)bindable.GetValue(BadgeColorProperty);
    }
}

}

//DroidBottomTabbedPageRenderer.cs

using System;
using System.Collections.Generic;
using System.Linq;

using Android.Content;
using Android.Support.Design.Widget;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android.AppCompat;
using View = Android.Views.View;
using AndroidRelativeLayout = Android.Widget.RelativeLayout;
using RelativeLayoutParams = Android.Widget.RelativeLayout.LayoutParams;

using Android.Support.Design.Internal;
using Xamarin.Forms.Platform.Android;
using System.ComponentModel;
using Android.Widget;
using Android.Graphics.Drawables;
using Android.Graphics.Drawables.Shapes;
using Android.Util;
using Android.Support.V4.View;

[assembly: ExportRenderer(typeof(ExtendedBottomTabbedPage), typeof(DroidBottomTabbedPageRenderer))]
namespace SchedulingTool.Droid.Renderers
{
public class DroidBottomTabbedPageRenderer : TabbedPageRenderer, BottomNavigationView.IOnNavigationItemReselectedListener
{
IDictionary<Page, string> _formsBadges;
List _androidBadges;

    bool _isShiftModeSet;
    int _l, _t, _r, _b, _width, _height, _tabsHeight;
    bool _firstTime;
    int _bottomBarHeight;
    Context _context;
    TabLayout _topBar;
    TabbedPage _tabbedPage;
    BottomNavigationView _bottomBar;
    AndroidRelativeLayout _container;
    RelativeLayoutParams _layoutParams;
    List<BottomNavigationItemView> _tabBarItems;
    ExtendedBottomTabbedPage _extendedTabbedPage;

    public DroidBottomTabbedPageRenderer(Context context) : base(context)
    {
        _context = context;
    }

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

        if (e.NewElement != null)
        {
            _tabbedPage = e.NewElement;
            _extendedTabbedPage = (ExtendedBottomTabbedPage)_tabbedPage;
            _firstTime = true;
            _tabBarItems = new List<BottomNavigationItemView>();
            _androidBadges = new List<TextView>();

            var children = GetAllChildViews(ViewGroup);

            foreach (var bottomNavItemView in children)
            {
                if (bottomNavItemView is BottomNavigationItemView)
                {
                    var tab = (BottomNavigationItemView)bottomNavItemView;
                    _tabBarItems.Add(tab);
                    AddBadge(tab);
                }
            }
            if (children.SingleOrDefault(x => x is BottomNavigationView) is BottomNavigationView bottomNav)
            {
                _bottomBar = bottomNav;
                _bottomBar.SetOnNavigationItemReselectedListener(this);
            }
            if(children.SingleOrDefault(x => x is AndroidRelativeLayout) is AndroidRelativeLayout container)
            {
                _container = container;
            }
            if (children.SingleOrDefault(x => x is TabLayout) is TabLayout topNav)
            {
                _topBar = topNav;
            }

            SetTabBadges();
            AddPropertyChangedHandlersForPages();
        }
    }

    protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        try
        {
            base.OnLayout(changed, l, t, r, b);

            _width = r - l;
            _height = b - t;
            _tabsHeight = Math.Min(_height, Math.Max(_bottomBar.MeasuredHeight, _bottomBar.MinimumHeight));

            _l = l;
            _t = t;
            _r = r;
            _b = b;

            if (!_isShiftModeSet)
            {
                _bottomBar.SetShiftMode(false, false);
                _isShiftModeSet = true;
            }
        }
        catch (Exception ex)
        {
            ExceptionHandler.LogException(this, nameof(OnLayout), ex);
        }
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        if (e.PropertyName == nameof(ExtendedBottomTabbedPage.BottomTabBarHidden))
        {
            HideTabbedPage();
        }
    }

    public async void OnNavigationItemReselected(IMenuItem item)
    {
        await _extendedTabbedPage.CurrentPage.Navigation.PopToRootAsync();
    }

    List<View> GetAllChildViews(View view)
    {
        if (!(view is ViewGroup group))
        {
            return new List<View> { view };
        }

        var result = new List<View>();

        for (int i = 0; i < group.ChildCount; i++)
        {
            var child = group.GetChildAt(i);

            var childList = new List<View> { child };
            childList.AddRange(GetAllChildViews(child));

            result.AddRange(childList);
        }

        return result.Distinct().ToList();
    }

    void AddPropertyChangedHandlersForPages()
    {
        foreach (var page in _extendedTabbedPage.Children)
        {
            page.PropertyChanged += OnPagePropertyChanged;
        }
    }

    void OnPagePropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == BottomTabbedPageExtensions.BadgeCountProperty.PropertyName)
        {
            var page = (Page)sender;
            UpdateBadgeForPage(page);
        }
    }

    void SetTabBadges()
    {
        var tabCount = _tabbedPage.Children.Count();
        _formsBadges = new Dictionary<Page, string>(tabCount);

        for (var i = 0; i < tabCount; i++)
        {
            var page = _tabbedPage.Children[i];
        }
    }

    void AddBadge(BottomNavigationItemView frame)
    {
        View badge = LayoutInflater.From(_context).Inflate(Resource.Layout.NotificationBadge, frame, false);
        frame.AddView(badge);
        TextView textViewBadge = (TextView)badge.FindViewById(Resource.Id.notifications_badge);

        var backgroundShape = CreateBackgroundShape();
        backgroundShape.Paint.Color = Colors.OrangeColor.ToAndroid();
        ViewCompat.SetBackground(textViewBadge, backgroundShape);

        _androidBadges.Add(textViewBadge);
    }

    void UpdateBadgeForPage(Page page)
    {
        if (_tabbedPage == null) return;

        var pageIndex = _tabbedPage.Children.IndexOf(page);
        var badgeCount = BottomTabbedPageExtensions.GetBadgeCount(page);

        if (!_formsBadges.ContainsKey(page))
        {
            _formsBadges.Add(page, page.Title);
        }

        var badge = _androidBadges[pageIndex];
        var tab = _tabBarItems[pageIndex];

        if (badgeCount <= 0)
        {
            badge.Visibility = ViewStates.Gone;
            return;
        }

        badge.Visibility = ViewStates.Visible;
        badge.Text = badgeCount > 99 ? "99+" : badgeCount.ToString();

    }

    void HideTabbedPage()
    {
        if (_firstTime)
        {
            _layoutParams = (RelativeLayoutParams)_bottomBar.LayoutParameters;
            _l = _layoutParams.LeftMargin;
            _t = _layoutParams.TopMargin;
            _r = _layoutParams.RightMargin;
            _b = _layoutParams.BottomMargin;
            _bottomBarHeight = _layoutParams.Height;
            _firstTime = false;
        }

        if (_extendedTabbedPage.BottomTabBarHidden)
        {
            _layoutParams.Height = 0;
            _bottomBar.LayoutParameters = _layoutParams;
            //_topBar.Visibility = ViewStates.Gone;
            //_bottomBar.LayoutParameters = new global::Android.Widget.RelativeLayout.LayoutParams(0,0);
            //_container.Invalidate();
            //_bottomBar.Visibility = ViewStates.Gone;
            //Measure(MeasureSpecFactory.MakeMeasureSpec(_width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(_tabsHeight, MeasureSpecMode.Exactly));
            //Layout(_l, _t, _r, _b);
        }
        else
        {
            _layoutParams.Height = _bottomBarHeight;
            _bottomBar.LayoutParameters = _layoutParams;
            //_topBar.Visibility = ViewStates.Visible;
            //_container.Invalidate();
            //_bottomBar.Visibility = ViewStates.Visible;
            //Measure(MeasureSpecFactory.MakeMeasureSpec(_width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(_tabsHeight, MeasureSpecMode.Exactly));
            //Layout(_l, _t, _r, _b);
        }
    }

    ShapeDrawable CreateBackgroundShape()
    {
        var radius = DpToPixels(12);
        var outerR = new float[] { radius, radius, radius, radius, radius, radius, radius, radius };
        return new ShapeDrawable(new RoundRectShape(outerR, null, null));
    }

    int DpToPixels(float dip)
    {
        return (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, dip, Resources.DisplayMetrics);
    }

}

public static class AndroidHelpers
{
    public static void SetShiftMode(this BottomNavigationView bottomNavigationView, bool enableShiftMode, bool enableItemShiftMode)
    {
        try
        {
            var menuView = bottomNavigationView.GetChildAt(0) as BottomNavigationMenuView;
            if (menuView == null)
            {
                System.Diagnostics.Debug.WriteLine("Unable to find BottomNavigationMenuView");
                return;
            }


            var shiftMode = menuView.Class.GetDeclaredField("mShiftingMode");

            shiftMode.Accessible = true;
            shiftMode.SetBoolean(menuView, enableShiftMode);
            shiftMode.Accessible = false;
            shiftMode.Dispose();


            for (int i = 0; i < menuView.ChildCount; i++)
            {
                var item = menuView.GetChildAt(i) as BottomNavigationItemView;
                if (item == null)
                    continue;

                item.SetShiftingMode(enableItemShiftMode);
                item.SetChecked(item.ItemData.IsChecked);

            }

            menuView.UpdateMenuView();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Unable to set shift mode: {ex}");
        }
    }
}

}

//ExtendedBottomTabbedPage.cs

using Xamarin.Forms;

namespace SchedulingTool.Renderers
{
public class ExtendedBottomTabbedPage : TabbedPage
{
#region Properties & Commands

    public static readonly BindableProperty TabBarHiddenProperty =
        BindableProperty.Create(nameof(BottomTabBarHidden), typeof(bool), typeof(ExtendedBottomTabbedPage), false);

    public bool BottomTabBarHidden
    {
        get { return (bool)GetValue(TabBarHiddenProperty); }
        set { SetValue(TabBarHiddenProperty, value); }
    }

    public enum BarThemeTypes { Light, DarkWithAlpha, DarkWithoutAlpha }

    public BarThemeTypes BarTheme { get; set; }

    public bool FixedMode { get; set; }

    #endregion

    #region Methods

    public void RaiseCurrentPageChanged()
    {
        OnCurrentPageChanged();
    }

    #endregion
}

}


Application crashes when we sent push notification from Firebase console

$
0
0

Dear All,
I developed xamarin forms androd application, implemented firebase console for push notification, whenever i send message from firebase application get crashed in debug mode am getting following error:

Java.Lang.RuntimeException: Unable to instantiate receiver com.google.firebase.iid.FirebaseInstanceIdInternalReceiver: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" on path: DexPathList[[zip file "/data/app/com.isat.GraduateGuru-tmLocHA5EVv0pwFs-XolYg==/base.apk"],nativeLibraryDirectories=[/data/app/com.isat.GraduateGuru-tmLocHA5EVv0pwFs-XolYg==/lib/arm64, /data/app/com.isat.GraduateGuru-tmLocHA5EVv0pwFs-XolYg==/base.apk!/lib/arm64-v8a, /system/lib64]]

I have enabled "Enable ProGuard" option in "Android options", Checked "Enabel Multi Dex" also. Added Proguard.cfg file and added bellow code

-dontwarn com.google.android.gms.**
-keep class com.google.android.gms.** { *; }
-keep class com.google.firebase.** { *; }

I make this file build action to "Progurad Configuration". but still getting that error. pls help me

thank you.

Bug Rendering Android

$
0
0

Hi,
as written in other posts, I'm building a new APP with all the updated libraries. Unfortunately I have these problems:
1. Shell application flickering on back navigation https://github.com/xamarin/Xamarin.Forms/issues/8581
2. briefly displaying a black screen when navigating back https://gitmemory.com/issue/xamarin/Xamarin.Forms/8581/571565579

for the first problem, the xamarin.forms 4.6 update appears to resolve, but is still in pre-release.

for the second, I saw that it depends on whether I have a splash_screen in android. Eliminate the splash_screen, the problem does not arise. other solutions I have not found.

Do you have more updated information?
Thanks

How to display List in Grid format

White Screen Issue while navigating in Xamarin forms Prism MasterDetails Page

$
0
0

White Screen Issue while navigating in Xamarin forms Prism MasterDetails Page

How to fix White Screen Issue while navigating in Xamarin forms Prism MasterDetails Page?

$
0
0

I have implemented MasterDetail Page using xamarin forms prism and I have following Pages in my app.
1) Master
2) Home
3) Employee
4) Profile

-- Initially App is set to Master - Home (Detail Page) page after login. From Home page i navigate to Employee (Detail Page) using code as follows :

await _navigationService.NavigateAsync("NavigationPage/Employee");

-- From Employee Page I navigate to Profile (Content Page - Non Detail page) by clicking on one of the employees using code:

await _navigationService.NavigateAsync("Profile", lstparam, null, false);

-- Once home button is clicked in profile page, i want to navigate to Master - Home (Detail Page) . However it navigates to Employee (Detail Page) .

await _navigationService.GoBackToRootAsync();

Checked navigation stack by debugging , It was only showing Employee (Detail Page) Page in it. Also tried navigation to home page by using following code :

await NavigationService.NavigateAsync("/Master/NavigationPage/Home");

The above code is working and i can navigate to Home (Detail Page) , but I am getting White Screen while navigating to Profile to Home Page .

Attached Screenshots . Please Help .Thanks in Advance.

1)Master

2)Home

3)Employee

4)Profile

5) file:///C:/Users/tkanekar/Desktop/Forum/Whitescreen.png

Prism, navigating to absolute URI

$
0
0

Hi,

I need to navigate to an absolute uri from the app. The syntax I'm using is "await _navigationService.NavigateAsync(new Uri("http://brianlagunas.com/", UriKind.Absolute));". I found the syntax online and I can't find much information about navigating to an absolute uri. I'm using Prism (Drylok) with Xamarin forms. When I clicked on the link nothing happened, and I didn't see any error messages. Relative navigation works fine. I only tested it with the simulators. What's the right way to navigate to an absolute uri? Thanks in advance!

Regards,
Lichang

There is an issue with my cart icon and cart items count.

$
0
0

Alignment of cart item and cart icon is not coming in a proper even when i'm using padding
in negative


How to stop menu icon navigation bar scrolling on tapped pages when swipe the tabbed pages..

Issues with JSON serialization in DEBUG and RELEASE mode

$
0
0

Hi

I am writing an app that de-serializes a JSON string into an object. The class that defines this object is inside a Shared (Portable) library and the reference to it is correctly added in the Xamarin.Forms app. The deserialization process works perfectly when the app is running in DEBUG mode. However, when I run it in RELEASE mode, there is an error that comes up :

"Unable to find a constructor to use for the type TypeName. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute."

The class did not have a constructor. So, I added one that actually does not do anything and have no argument. The error still occured. I added the JsonConstructor attribute and still the error occurs. I signed the Shared Portable project, but it still occurs. It is happening only in RELEASE mode, not in DEBUG mode.

Any assistance you may provide will be much appreciated.

Regards

Terence

Increase AppBarButton height in UWP

$
0
0

I am trying to modify the style of the AppBarButton, but I have got no luck in trying to override the base style in App.xaml. I believe, I need to set this style at runtime to take effect, but I don't know how to do that. Is there any other way, like using a custom renderer?
Something like this:

public class WindowsContentPageRenderer : PageRenderer
   {
       protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
       {
           base.OnElementChanged(e);
           if (e.OldElement != null && Element == null)
               return;
           Loaded += OnLoaded;
       }

       private void OnLoaded(object sender, RoutedEventArgs args)
       {
           var myPanel = ContainerElement as AppBarButton;
           if (myPanel != null)
           {
               myPanel.Height = 48;
               myPanel.MaxHeight = 48;
           }
       }
   }

But, the ContainerElement as AppBarButton always returns a null.

Please help, thank you :smile:

White screen instead Page duaring navigation

$
0
0

Hello!

I have a problem with my project. I use MasterPageDetail in my XF app. Detail page is navigation page. To navigate ahead i use PushAsync in my Detail page. To close page manualy PopAsync.

When i tap only back button (iOS project) it works fine, but if i use PopAsync after Back button, i see white screen instead previous page in navigation stack. In this case in native renderer of my navigation page i get null in PopViewController and this raise exception.

Can somebody help me?

Problem opening iOS Storyboard

$
0
0

System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> MonoTouch.Design.Client.InvalidSessionException: Error in the application.
at MonoTouch.Design.Client.ServerProcessConnection.SendRequest(CommandRequest req, Boolean throwIfNotRunning) in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 235
at MonoTouch.Design.Client.ServerProcessConnection.SendRequest[TResponse](CommandRequest req, Boolean throwIfNotRunning) in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 252
at MonoTouch.Design.Client.ServerProcessConnection.CreateSession() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 111
at MonoTouch.Design.Client.ServerProcessConnection.b__28_0() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 116
at System.Threading.Tasks.Task1.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject) --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task1.get_Result() at MonoTouch.Design.Client.IPhoneDesignerSession.<>c__DisplayClass289_11.b__1(Task1 t) in E:\A\_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 2072 at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at MonoTouch.Design.Client.IPhoneDesignerSession.<>c__DisplayClass289_01.<EnsureSession>b__0() in E:\A\_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 2146 at System.Threading.Tasks.Task1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MonoTouch.Design.Client.IPhoneDesignerSession.d__191.MoveNext() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 750
--- End of stack trace from previous location where exception was thrown ---
at MonoTouch.Design.Client.IPhoneDesignerSession.d__191.MoveNext() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 757
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MonoTouch.Design.Client.IPhoneDesignerSession.d__190.MoveNext() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 735
--- End of stack trace from previous location where exception was thrown ---
at MonoTouch.Design.Client.IPhoneDesignerSession.d__190.MoveNext() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 743
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at MonoTouch.Design.Client.IPhoneDesignerSession.d__186.MoveNext() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 624
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MonoTouch.Design.Tasks.d__1.MoveNext() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Shared\TaskExtensions.cs:line 28
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MonoTouch.Design.Client.IPhoneDesignerSession.d__185.MoveNext() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 576
---> (Inner Exception #0) System.AggregateException: One or more errors occurred. ---> MonoTouch.Design.Client.InvalidSessionException: Error in the application.
at MonoTouch.Design.Client.ServerProcessConnection.SendRequest(CommandRequest req, Boolean throwIfNotRunning) in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 235
at MonoTouch.Design.Client.ServerProcessConnection.SendRequest[TResponse](CommandRequest req, Boolean throwIfNotRunning) in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 252
at MonoTouch.Design.Client.ServerProcessConnection.CreateSession() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 111
at MonoTouch.Design.Client.ServerProcessConnection.b__28_0() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 116
at System.Threading.Tasks.Task1.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject) --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task1.get_Result() at MonoTouch.Design.Client.IPhoneDesignerSession.<>c__DisplayClass289_11.b__1(Task1 t) in E:\A\_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\IPhoneDesignerSession.cs:line 2072 at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
---> (Inner Exception #0) MonoTouch.Design.Client.InvalidSessionException: Error in the application.
at MonoTouch.Design.Client.ServerProcessConnection.SendRequest(CommandRequest req, Boolean throwIfNotRunning) in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 235
at MonoTouch.Design.Client.ServerProcessConnection.SendRequest[TResponse](CommandRequest req, Boolean throwIfNotRunning) in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 252
at MonoTouch.Design.Client.ServerProcessConnection.CreateSession() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 111
at MonoTouch.Design.Client.ServerProcessConnection.b__28_0() in E:\A_work\283\s\Xamarin.Designer.iOS\MonoTouch.Design.Client\Connection\ServerProcessConnection.cs:line 116
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)<---
<---

Increase performance of CollectionView using Grid with configurable columns as ItemTemplate

$
0
0

Dear Xamarin Community,

I have recently converted all my Listviews to Collectionviews to increase the performance. This works great, but I'm looking to increase the performance even more when it comes to the layout used as the ItemTemplate.

Specifications:

  • Multiple columns where the width for each column is configurable. I need to be able to change the width on all columns and also hide columns by setting the width to 0. In the same way it should be possible show columns with default width 0 by setting the width.
  • The widht of the columns should be relative to each other to not create a massive breaking change in configurations. The width of each column is today binded to a GridLength property that uses GridLength.Star for width > 0 and GridlLength.Absolute if the width is 0.
  • The height must be dynamic. Each column consist of a single label. All the information in each label must be shown, so the height needs to adapt to the length of the labels.
  • It is desirable to be able to add custom columns in runtime. This is not possible in the current solution, but there is a high demand for this feature. This is not a part of increasing the performance, and not an absolute must at this time, so don't be shy to shout out some performance tips if you don't have a solution for this part.

Current Implementation:

<CollectionView x:Name="OrderCollectionView" Grid.Row="2" Grid.Column="0" ItemsSource="{Binding Orders}" SelectedItem="{Binding SelectedOrder, Mode=TwoWay}" SelectionMode="Single" SelectionChangedCommand="{Binding SelectionChangedCommand}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <CustomGrid.ColumnSpacing="5" Padding="5,10,5,0">
                <CustomGrid.GestureRecognizers>
                    <TapGestureRecognizer Command="{Binding Source={x:Reference OrderCollectionView}, Path=BindingContext.ItemTappedCommand}" CommandParameter="{Binding .}"/>
                </CustomGrid.GestureRecognizers>
                <CustomGrid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="6"/>
                </CustomGrid.RowDefinitions>
                <CustomGrid.ColumnDefinitions>
                    <ColumnDefinition Width="{Binding OrdernoColumnWidth, Mode=TwoWay}" BindingContext="{Binding Source={x:Reference OrderCollectionView}, Path=BindingContext}"/>
                    <ColumnDefinition Width="{Binding CustomernoColumnWidth, Mode=TwoWay}" BindingContext="{Binding Source={x:Reference OrderCollectionView}, Path=BindingContext}"/>
                    <ColumnDefinition Width="{Binding CustomernameColumnWidth, Mode=TwoWay}" BindingContext="{Binding Source={x:Reference OrderCollectionView}, Path=BindingContext}"/>
                    <ColumnDefinition Width="{Binding OrderlinesColumnWidth, Mode=TwoWay}" BindingContext="{Binding Source={x:Reference OrderCollectionView}, Path=BindingContext}"/>
                    <ColumnDefinition Width="{Binding PackagesColumnWidth, Mode=TwoWay}" BindingContext="{Binding Source={x:Reference OrderCollectionView}, Path=BindingContext}"/>
                    <ColumnDefinition Width="{Binding WeightColumnWidth, Mode=TwoWay}" BindingContext="{Binding Source={x:Reference OrderCollectionView}, Path=BindingContext}"/>
                </CustomGrid.ColumnDefinitions>
                <Label Text="{Binding Path=[orderno]}" Grid.Column="0" FontSize="17" VerticalTextAlignment="Center"/>
                <Label Text="{Binding Path=[customerno]}" Grid.Column="1" FontSize="17" VerticalTextAlignment="Center"/>
                <Label Text="{Binding Path=[customername]}" Grid.Column="2" FontSize="17" VerticalTextAlignment="Center"/>
                <Label Text="{Binding Path=[orderlines]}" Grid.Column="3" FontSize="17" VerticalTextAlignment="Center"/>
                <Label Text="{Binding Path=[packages]}" Grid.Column="4" FontSize="17" VerticalTextAlignment="Center"/>
                <Label Text="{Binding Path=[weight]}" Grid.Column="5" FontSize="17" VerticalTextAlignment="Center"/>
                <BoxView HeightRequest="1" BackgroundColor="#BDBDBD" Grid.Row="1" Grid.ColumnSpan="6" Margin="-5,5,-5,0" VerticalOptions="End"/>
            </CustomGrid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

To hide the columns with width = 0 I use a custom controller that inherits from Grid. The only thing this does is to override the OnSizeAllocated to set the HeightRequest to 0 if the width is 0 to completely hide the column, and set it to -1 to get the auto height back. Not sure if this is still needed, but it was in older versions of Xamarin forms. It also seems like setting the height back to -1 does not work as intended anymore. Implementation of the custom Grid:

 public class CustomGrid : Grid
    {
        protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);

            foreach (View child in Children)
            {
                if (child.Width == 0 || child.Width < -1)
                    child.HeightRequest = 0;
                else
                    child.HeightRequest = -1;
            }
        }
    }

Problem:
With one or two columns it works just fine. With 5-6 columns the performance is not like it should be, even if half of the columns are hidden with width = 0. I guess they are included in the measurement of the layout anyway, so it doesn't really matter if they are visible or not(?). When assigning some items to the ItemSource, populating the Collectionview "lags". You can see each item beeing added one by one, while with fewer columns they all pop up at the same time without the lagging experience. I'm aware that using Height = Auto in a Grid is a performance hit, and if I change this part the performance is a lot better. But I still need to display all the information in the labels, which means that the height will vary, and I haven't found another good solution for this.

I see a lot of cool stuff with great performance arround the community, so I hope there is someone out there with some knowledge they would like to share about increasing the performance of this kind of layout. It will be greatly appreciated!

Redirecto to a View from ViewMOdel

$
0
0

I am filtering a list in a view model, but after that is done i need to be redirected to another page with the data. This is how i am doing it at the moment, but the page has no navigation bar even though i have set it to true in xaml and once i press one item i get an error My error System.InvalidOperationException: 'PushAsync is not supported globally on Android, please use a NavigationPage.'

      My filter View Model
      bool _filterAllItems;
      public bool FilterAllItems
        {
            set
            {
                _filterAllItems = value;
                NotifyPropertyChanged();

                if (_filterAllItems)
                {
                    _parentCategoryId = -1;
                    FillArticles();
                     Application.Current.MainPage.Navigation.PushModalAsync(new ArticlesForPurchaseFiltered());


                }

            }
            get => _filterAllItems;
        }

this is how i am selecting the item in the content page

 private async void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
            {
    #if !NAVIGATION
                var selectedItem = ((ListView)sender).SelectedItem;
                var articlePage = new MyArticle(selectedItem as ArticleDetailData);

                await Navigation.PushAsync(articlePage);
    #endif

        }

Can you please suggest how to redirect to View page from View model so i dont use
Application.Current.MainPage.Navigation.PushModalAsync(new ArticlesForPurchaseFiltered());


Custom Entry propert not reflected to child behavior

$
0
0

I have a view page with multiple same entry associated with the same behavior. So, I create a custom separate view and insert it to the view page.

<?xml version="1.0" encoding="UTF-8"?>
<local:RoundedEntry xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:TravelRecord"
             WidthRequest="100"
             Style="{StaticResource RoundedEntryStyle}"
             x:Class="TravelRecord.CustomEntryCell">

    <local:RoundedEntry.Behaviors>
        <local:EntryEmptyValidationBehaviour />
    </local:RoundedEntry.Behaviors>

</local:RoundedEntry>

The page

<local:CustomEntryCell Placeholder="First Name" Text="{Binding User.FirstName.Value}" />

<local:CustomEntryCell Placeholder="Last name" Text="{Binding User.LastName.Value}" />

<local:CustomEntryCell Placeholder="User name" Text="{Binding User.Username.Value}" />

But, fortunately the placeholder name doesn't reflected to the child behavior (always null)

protected override void OnAttachedTo(RoundedEntry bindable)
{

    control = bindable;
    _placeHolder = bindable.Placeholder;
    _placeHolderColor = bindable.PlaceholderColor;
    bindable.TextChanged += OnEntryTextChanged;
}

_placeHolder is empty even it's there in the view

Display Xamarin Font Icons From Stored Data

$
0
0

Hello! What is the best way to display font icons with data being pulled from a web service? I want to store the value of the icon and display the icon similar to the rest of the information, but with a custom font icon.

I have a xamarin forms app working with data from a webservice successfully. Here is my model.

public class TypeModel
{
    [PrimaryKey]
    public int pType { get; set; }

    public int fDepartment { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public string Icon { get; set; }

    public string Version { get; set; }

}

I also got the font icons working successfully like the tutorial at [1]: https://montemagno.com/using-font-icons-in-xamarin-forms-goodbye-images-hello-fonts/ I got my icons stored under this class. Trying to transition to managing these values with web service or array if I have too now.

public const string IconCheckMark = "\uf12c";

public const string IconSearchGlass = "\uf349";

public const string IconQuestionMark = "\uf2d6";

public const string IconQuestionCircle = "\uf2d7";

But here is where my problem starts. My ViewModel is doing the work to create the collection. How do I assign a value that will display and match correctly.

public ObservableCollection<TypeModel> TypesCollection { get; set; }

TypesCollection.Clear();

IEnumerable<TypeModel> types = await DataSource.GetTypes();

foreach (var key in types)
{
    \\Original value doesn't display correctly, shows like \U f 1 2 c when debugging on emulator
    \\key.Icon = key.Icon;

    \\Works and displays correctly but static data displays one icons for all
    \\key.Icon = "\uf12c";

    \\Works and displays correctly but static data displays one icons for all
    \\key.Icon = FontClass.IconCheckMark;

    TypesCollection.Add(key);    
}

Nice and simple after that for the xaml files.

<ResourceDictionary>

    <OnPlatform x:Key="IconFonts" x:TypeArguments="x:String">

        <On Platform="iOS" Value="Material Design Icons"></On>

        <On Platform="Android" Value="IconFonts.ttf#Material Design Icons"></On>

        <On Platform="UWP" Value="/Assets/IconFonts.ttf#Material Design Icons"></On>

    </OnPlatform>

</ResourceDictionary>

<Label FontFamily="{StaticResource IconFonts}" Text="{Binding Icon}"></Label>

App window shrinks in android

$
0
0

Anyone experienced this phenomena ?
App mainwindow shrinks and get stuck in this mode and I can't get it to maximise again.
I haven't found out when the app enters this mode or if it is some gesture I do, but its operational in this mode and app works.
I have this in the manifest
android:supportsPictureInPicture="false" android:resizeableActivity="false"


blur background effect for frame

$
0
0

Hello,

I need an effect to blur the background for frame or stacklayout. Is there a native render that can do this for android and ios?

Thx

How create blurred Page

$
0
0

Hi, anyone know how create blurred view using Xamarin.Forms?

Viewing all 77050 articles
Browse latest View live


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