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

Play sound

$
0
0

Hi guys, I'm newbie in Xamarin and c# and I'm trying do make an app for android and iOS in which I've to play a sound, like a beep or notification.
Searching on google for the simplest solution, I found some info about my issue, so I tried do this:

  • Installation of "MediaManager for Xamarin" packet
  • Into mypage.cs I put "using Plugin.MediaManager;"
  • Into a button's Handle_Clicked I put this code: await CrossMediaManager.Current.Play("http://www.montemagno.com/sample.mp3");

In the app's debug when I click the button I receive this exception:
This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.

I can't understand the message; could someone help me, please?

Thanks in advance


Working with resource dictionary in both XAML and code behind

$
0
0

Is it possible to define global styles in both App.xaml and App.xaml.cs, but access these resources solely from XAML? Would these get compiled into a single resource dictionary? Is it possible to define a style in App.xaml and reference it in App.xaml.cs and vice versa?

Why I ask: I am currently implementing a font manager to provide better cross-platform font style/size.

Masonry-like lib for Xamarin Forms

$
0
0

Hello :)

I am looking for a Masonry-like layout (https://masonry.desandro.com/) in my Xamarin Forms app.
So far i haven't found any lib that could help me with this.

Do anyone have any tips for this? Either how to solve it by myself, a free lib or a paid lib to use.

Best Regards,
Tobias

How to Store user login credential in Xamarin.Form

$
0
0

i am very new in xamarin form and i able to call webservice and login..now i want to store the username and password of user locally. i have search a lot on the web and can't find a working solution. i have seen this official site that recommend to use Xamarin.Auth to store in keychain and keystroke but the tutorial in on Xamarin.IOS and Xamarin.Android which i dont know how to convert to Xamarin.Form.
https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/general/store-credentials/

a little bit help on how to make this to work in Xamarin.Form is very much appreciate.
and i think the Xamarin Documentation need a lot of improvement on this.
Thank you very much

KeyboardOverlapRenderer issue with iOS. Bottom Margin not show after keyboard overlap.

$
0
0

keyboard overlap not working after click on textbox.

As per my screen shot without click on textbox its working fine with bottom padding(Screen Shot #1). But after click on textbox bottom margin not working using KeyboardOverlapRenderer(Screen Shot #2) .

Screen Shot #1

Screen Shot #2

Please help me out.

Thanks in Advance!

Localizing problem in UWP Store App

$
0
0

I just noticed that the localizing for my UWP app does not work correctly.
From a listview I select my language:
strings.Culture = new CultureInfo("en-GB");

After this I set the text for my controls like this:
MyControl.Text = strings.MyText;

This just works fine on Android and iOS. Even in debug mode on UWP.
But when I install the AppPackage on my phone it does not work anymore.

Open file using UIDocumentInteractionController

$
0
0

Hi all,

I am working on Xamarin Forms application. The app currently downloads files from URL and save it in Documents directory of the phone. What I intend to achieve now is to view those downloaded files on Button Click. The app popups the default programs available to open the file.

I've done so in android. But I am having problems in iOS. I am using "UIDocumentInteractionController" to view the files. But the button click event doesn't display any options.

Following is my code sample. Please help.

`
public partial class ViewController : UIViewController
{
string filePath;
string fileName;

public override void ViewDidLoad()
{
    base.ViewDidLoad();

    filePath = "/Users/user/Library/Developer/CoreSimulator/Devices/6A3459AC-A7BC-40CE-A3F9-6581215E3421/data/Containers/Data/Application/BC5B26E9-ABD9-4310-96F0-57194837A73E/Documents/test1.pptx";

    var buttonO = new UIButton(UIButtonType.RoundedRect) {
        Frame = UIScreen.MainScreen.Bounds,
        BackgroundColor = UIColor.Red
    };

    NSString urlString = new NSString(filePath);
    NSUrl myFileUrl = new NSUrl(urlString);
    Console.WriteLine(myFileUrl.AbsoluteString);
    string absPath = myFileUrl.Path;

    buttonO.TouchUpInside += (sender1, e1) => {
        System.Diagnostics.Debug.WriteLine("File Path: " + filePath);

        // CALL FUNCTION
        OpenFileFunc();
    };

    Add(buttonO);
}

public void OpenFileFunc()
{
    var viewer = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(filePath));
    var controller = GetVisibleViewController();
    viewer.PresentOpenInMenu(controller.View.Frame, controller.View, true);

}

private UIViewController GetVisibleViewController(UIViewController controller = null)
{
    controller = controller ?? UIApplication.SharedApplication.KeyWindow.RootViewController;

    if (controller.PresentedViewController == null)
        return controller;

    if (controller.PresentedViewController is UINavigationController) {
        return ((UINavigationController)controller.PresentedViewController).VisibleViewController;
    }

    if (controller.PresentedViewController is UITabBarController) {
        return ((UITabBarController)controller.PresentedViewController).SelectedViewController;
    }

    return GetVisibleViewController(controller.PresentedViewController);
}

}
`

How to pass data back to previous page in Xamarin Forms?

$
0
0

How do I pass selected Item of list view present in one page to the previous page in Xamarin. Forms?
Please Help


how to use command parameter in listview?

System.ObjectDisposedException: Cannot access a disposed object when using ScrollView

$
0
0

I have a Xamarin.Forms app that includes a ContentPage with a ScrollView, where the ScrollView is initially hidden, but in response to a UI event I show it by setting IsVisible to true and calling ScrollToAsync on the ScrollView. After recently upgrading Xamarin.Forms, this causes this exception:

Xamarin caused by: android.runtime.JavaProxyThrowable: System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Xamarin.Forms.Platform.Android.ScrollViewRenderer'.
Java.Interop.JniPeerMembers.AssertSelf(IJavaPeerable self)<3a653d21f22f4786bf9d5acf69f4a22e>:0
Java.Interop.JniPeerMembers.JniInstanceMethods.InvokeVirtualBooleanMethod(string encodedMember, IJavaPeerable self, JniArgumentValue* parameters)<3a653d21f22f4786bf9d5acf69f4a22e>:0
Android.Views.View.get_IsLayoutRequested()<cba5498252974515814d3da6e57d094c>:0
Xamarin.Forms.Platform.Android.ScrollViewRenderer.<OnScrollToRequested>d__44.MoveNext()<15c9790557774c809371f43133cc42c4>:0
Android.App.SyncContext.<>c__DisplayClass2_0.<Post>b__0()<cba5498252974515814d3da6e57d094c>:0
Java.Lang.Thread.RunnableImplementor.Run()<cba5498252974515814d3da6e57d094c>:0
Java.Lang.IRunnableInvoker.n_Run(IntPtr jnienv, IntPtr native__this)<cba5498252974515814d3da6e57d094c>:0
at (wrapper dynamic-method) System.Object:ba3ec2cc-2626-44c0-ab76-80f16217bdbf (intptr,intptr)
mono.java.lang.RunnableImplementor.n_run(Native Method)
mono.java.lang.RunnableImplementor.run()RunnableImplementor.java:30
android.os.Handler.handleCallback()Handler.java:739
android.os.Handler.dispatchMessage()Handler.java:95
android.os.Looper.loop()Looper.java:158
android.app.ActivityThread.main()ActivityThread.java:7229
java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run()ZygoteInit.java:1230
com.android.internal.os.ZygoteInit.main()ZygoteInit.java:1120

I managed to find a workaround, which is to call ScrollToAsync like this:

public async Task DelayActionAsync(int delay, Action action)
{
    await Task.Delay(delay);

    action();
}

and replace my ScrollToAsync call with this:

 DelayActionAsync(100, () => {myScrollView.ScrollToAsync(positionX, positionY, false);} );

and this gets rid of the crash (sorry for any errors, this is typed from memory).

My question is, why do I have to do this? Is this just a bug in Xamarin.Forms that I am working around, or is this the recommended and correct way, and I was just lucky it wasn't crashing previously? If the latter, can anyone point me to any documentation about why this is so?

The crash only occurred on certain Android devices, and only in release builds. That doesn't mean it's a Xamarin bug of course because it could be a timing bug in my code that only gets triggered on certain devices. I just want to know how to code defensively to avoid these errors.

Bluetooth printing

$
0
0

I am looking for a way to connect to a handheld bluetooth printer to print receipts from an application. It must be useable on iOS, Android and UWP.
Are there any plugins that will allow me to connect to a printer via bluetooth and pass data over to be printed? Any help/tips on this at all would be great.

Thanks.

Addition of days to fromDate

$
0
0

How to add number of days to fromDate in datepicker based on number of days selected in a picker.Also after adding the days the previous dates should be disabled.Please help me with the answer.

IOS Custom Renderer Entry Right Margin Not Working

$
0
0

Hi, im currently trying to duplicate an Entry for IOS to be the same as the Android Entry Style. The problem im facing is that when setting the Margins for the custom entry on ios the right margin does not seem to take effect. Here are some examples

    <StackLayout>
        <local:MyIOSEntry Placeholder="First Name" Margin="45,0,45,0"></local:MyIOSEntry>
    </StackLayout>

    <StackLayout>
        <toolkit:EntryLine
        WidthRequest="50"
                   Text="{Binding Email}"
                   Keyboard="Email"
                   Margin="45,0,45,0"
                   Placeholder="email address"
                   x:Name="EntryEmail"
                   StyleId="EmailTextField"
                   IsEnabled="{Binding IsNotBusy}"
                   BorderColor="#ECECEC">
        </toolkit:EntryLine>
    </StackLayout>

    <StackLayout>
        <Entry Placeholder="First Name" Margin="45,0,45,0"></Entry>
    </StackLayout>

OUTPUT

So on the first entry the right Margin for my custom renderer the right margin it not in its correct spot

the second entry i put a Xamarin Form Toolkit Entry which completely spans off the screen even with a right margin set.

the third entry works fine but the entry is ugly and need to duplicate an android style entry field

here is my IOS entry custom renderer as to which i also found on the forums.

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

        if (Control != null)
        {
            Control.BorderStyle = UITextBorderStyle.None;

            var view = (Element as MyIOSEntry);
            if (view != null)
            {
                DrawBorder(view);
                SetFontSize(view);
                SetPlaceholderTextColor(view);
            }
        }
    }



    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        base.OnElementPropertyChanged(sender, e);

        var view = (MyIOSEntry)Element;

        if (e.PropertyName.Equals(view.BorderColor))
            DrawBorder(view);
        if (e.PropertyName.Equals(view.FontSize))
            SetFontSize(view);
        if (e.PropertyName.Equals(view.PlaceholderColor))
            SetPlaceholderTextColor(view);
    }


    void DrawBorder(MyIOSEntry view)
    {
        var borderLayer = new CALayer();
        borderLayer.MasksToBounds = true;
        borderLayer.Frame = new CoreGraphics.CGRect(0f, Frame.Height / 2, Frame.Width, 1f);
        borderLayer.BorderColor = view.BorderColor.ToCGColor();
        borderLayer.BorderWidth = 1.0f;

        Control.Layer.AddSublayer(borderLayer);
        Control.BorderStyle = UITextBorderStyle.None;
    }

    void SetFontSize(MyIOSEntry view)
    {
        if (view.FontSize != Font.Default.FontSize)
            Control.Font = UIFont.SystemFontOfSize((System.nfloat)view.FontSize);
        else if (view.FontSize == Font.Default.FontSize)
            Control.Font = UIFont.SystemFontOfSize(17f);
    }

    void SetPlaceholderTextColor(MyIOSEntry view)
    {
        if (string.IsNullOrEmpty(view.Placeholder) == false && view.PlaceholderColor != Color.Default)
        {
            var placeholderString = new NSAttributedString(view.Placeholder,
                                        new UIStringAttributes { ForegroundColor = view.PlaceholderColor.ToUIColor() });
            Control.AttributedPlaceholder = placeholderString;
        }
    }

}

}

Can anyone see why the right margin is not taking effect. seems like such a sime problem. i've tryied moving all the entrys and putting them in 1 stacklayout with the margin set in the stacklayout but has no difference.

thanks

The first entry



Error in button click where null values are passed

$
0
0

Hi, I have a written a code for Applyleave by calling the api. It has only request model.No response model.So I compared the values of employeeid from login and employee id from the applyleaverequestmodel. But it is taking null values.Please help me with the code.

Api class
public static async Task PostAsyncMethod(Object model, string url)
{
try
{
var result = await client.PostAsJsonAsync(url, model);
if (result.IsSuccessStatusCode)
{
string res = await result.Content.ReadAsStringAsync();
return res;
}
else
{
return null;
}
}
catch (Exception ex)
{

        }
        return null;
    }

apply leave code behind-

    private async void ApplyLeave_Button_Clicked(object sender, EventArgs e)
    {
        try
        {
            ApplyLeaveRequestModel empid = new ApplyLeaveRequestModel();
            empid.EmployeeId = loginResponseModel.Id;
             var res = await ApiClass.PostAsyncMethod(empid, ApiClass.applyLeave);
            if(loginResponseModel.Id==applyLeaveRequestModel.EmployeeId)
                await DisplayAlert("Leave", "Leave Successfull", "OK");
        }
        catch (Exception ex)
        { }
    }

Please help me in correcting the error.

Pre-release: Xamarin.Forms 2.3.5.256-pre6

$
0
0

We've pushed Xamarin.Forms 2.3.5.256-pre6 to NuGet and have begun QA in preparation for making this our next stable release.

To install the pre-release, check the pre-release option in your NuGet manager and install this version.

For some quick highlights, check out our blog announcement. Hint: Fast Renders for Android, ListView performance enhancements and fixes, and MacOS preview.

If you’ve got a bug to report, drop us a quick report here so we can troubleshoot in detail.

As you have performance specific feedback, please join the discussion in this performance specific thread.

Important notes

  • Xamarin.Forms is now compatible with .NET Standard projects! Not all build features may work.
  • Behavior change: Device.RuntimePlatform now returns WinRT on WinRT and UWP on UWP.
  • Behavior change: Using the new AutomationProperties may impact UI Test execution on Android. AutomationId, Name, and HelpText will all set the native ContentDescription property, with Name and/or HelpText taking precedence over AutomationId (Name and HelpText will be concatenated). This means that any tests looking for AutomationId will now fail if Name and/or HelpText are also set on that element. To work around this issue, please alter your UI Tests to look for the value of Name/HelpText in this scenario.
  • Behavior change: Calling Focus on a Picker on WinRT/UWP will now open the drop down.
  • Deprecation: Android IVisualElementRenderer.ViewGroup is now obsolete. Please use View instead.

2.3.5.256-pre6

  • 56795 - "DataTriggers do not work on UWP in RELEASE mode"

2.3.5.255-pre5

  • [Android] Dispose check before setting properties on Button (PR)
  • 36031 - "Button border not drawn on Android without a BorderRadius" (PR)
  • 57717 - "Setting background color on Button in Android FormsApplicationActivity causes NRE" (PR)
  • 57749 - "[UWP] After enabling a disabled button it is not clickable" (PR)
  • [Android] Dispose check on FastButtonRenderer to prevent crash (PR)
  • [Android] Set the Id field for Android Views created by Forms (PR)
  • 55588 - "Cannot open more than one ContextAction in different ListViews on IOS" (PR)
  • 56444 - "A small "dot" shows up as value in Android labels when the value is null/empty." (PR)
  • 56895 - "VS2017 stable - previewer exception crash- no method found Button_click on type" (PR)
  • 56896 - "ListViews for lists with many elements regressed in performance on iOS" (PR)
  • 57108 - "Fix possible crash on API 21+ at launch when using Holo theme and FormsApplicationActivity" (PR)

Release Notes

2.5.3.239-pre3

Release Notes

2.3.5.235-pre2

Release Notes

2.3.5.233-pre1

Release Notes


Issues with last version 4.2.0.703

$
0
0

Hi,

I used Xamarin 4.1.1.3 then I update to the last stable version 4.2.0.703.

Then I start a new project (VS 2015 update 3) with a Blank App (Xamarin.Forms Portable). I keep only the PCL project and the Android project.
Then I go on ‘Manage Nuget Packages for the solution’ and I see that :

  • Xamarin Forms is with version 2.2.0.45
  • There are 5 packages Xamarin.Android.Support .. version 23.0.1.3

Why XF is not to the last version 2.3.2.127 ? Why 2.2.0.45 ?

Then I begin to update XF 2.2.0.45 --> 2.3.2.127. It says that it updates also the 5 packages from 23.0.1.3 to 23.3.0 and it add 2 new packages : Xamarin.Android.Support.v7.RecyclerView and Xamarin.Android.Support.Vector.Drawable. Why ?

Then it say in a yellow line : Xamarin.Forms 2.2.0.45 failed to uninstall. Restart Visual Studio to finish the process. I do Restart then Clean Solution / Rebuild. --> ‘Rebuild all successed’ but there is a warning : Found conflicts between different versions of the same dependent assembly. I do a double click on the warning .

Then I run debug with emulator (API 23) and now it is OK.

Why is there always such problems ? is it DLL hell which is come back ?

Thanks for answers

How would I produce a Cell View that Looks like the Image below

$
0
0

Hi all,

I was wondering if it's possible in Xamarin Forms to produce a layout like that seen in this image?

I'm mostly referring to the listview of images and text. This is as far as I have got at the moment..

  class CustomJobCell : ViewCell
    {
      public CustomJobCell()
        {
            //instantiate each of our views
            var image = new Image();
            var JobTitle = new Label();
            var Salary = new Label();
            var Location = new Label();
            var verticaLayout = new StackLayout();
            var horizontalLayout = new StackLayout() { BackgroundColor = Color.White };

            //set bindings
            JobTitle.SetBinding(Label.TextProperty, new Binding("Name"));
            Salary.SetBinding(Label.TextProperty, new Binding("Salary"));
            Location.SetBinding(Label.TextProperty, new Binding("Location"));
            image.SetBinding(Image.SourceProperty, new Binding("Image"));

            //Set properties for desired design
            horizontalLayout.Orientation = StackOrientation.Horizontal;
            horizontalLayout.HorizontalOptions = LayoutOptions.Fill;
            verticaLayout.HorizontalOptions = LayoutOptions.FillAndExpand;
            verticaLayout.VerticalOptions = LayoutOptions.FillAndExpand;
            verticaLayout.Padding = new Thickness(20);
            image.Aspect = Aspect.AspectFit;
            image.
            JobTitle.FontSize = 24;

            //add views to the view hierarchy
            verticaLayout.Children.Add(image);
            verticaLayout.Children.Add(JobTitle);
            verticaLayout.Children.Add(Salary);
            verticaLayout.Children.Add(Location);
            horizontalLayout.Children.Add(verticaLayout);

            // add to parent view
            View = horizontalLayout;
        }
    }

Now I will show you the image of what I have achieved so far..:

The way this is set up is that this is a list view and within the listview there are CustomCell objects for each cell. My problem is that I need the image to be held in some sort of frame so that it doesn't push the text outside of the cell view.

I would then need to display the two labels underneath it. I feel like I'm close but I couldn't find any extra information.

Sorry for bothering you!

J

DatePicker Formats

$
0
0

Is there documentation for the different format options for a DatePicker when using Xamarin forms.

In the one of the guides I found I could set the Format ="D"

Is there a list somewhere that shows the other formats (other than "D"). I checked the api but didn't see a list of formats.

I appreciate the help.

Xamarin Forms Application issues when deploying

$
0
0

We started testing our app on android and while in general it works well we ran into an odd issue

Right after installing the APK and starting the app and then using the home button and then clicking on the app again it did things that shouldnt happen. Problem was the app is using a passcode screen on resume and so i thought it was some of my code. The problem does not happen in the simulator or running on the device in the debugger. The only time this happens is from an APK install

i removed a bunch of my code to try an track this down but so far nothing. What happens is that right after installing and launching the app the screen comes up. Hit the home button. click the app icon again, click the home button, click the app icon again and now all i get is a white screen. If i hit the home button again and the icon again and do this a few more times when i am on the white screen and use the back button it goes back one time for each use of the home button and then on the final one it crashes.

in order to hunt this issue down i created a simple app in Visual Studio. Just the default application (portable) and deployed as an APK and sure enough it is doing a similar thing

After installing and launching the main screen shows
hit home button
hit app icon again and it shows the main screen
hit home button
hit app icon again and it shows the main screen
hit home button
hit app icon again and it shows the main screen

now if you hit the back button the screen flashes and shows the main screen again (almost like navigating back but i dont have a regular contentpage as a mainpage).
the back button does this for as often as you did the home button/app icon thing above and then you go back to the phone screen

it only does all this the first time it is launched after installing.

so my questions.

1) Anyone have any idea what this could be?

2) In a case like this (only a release APK will show the issue) how can i debug a problem like this?

thanks for any help

NullReferenceException on Grid.CalculateAutoCells [Only XF iOS]

$
0
0

Hi,

I'm developing an app with Xamarin Forms from 7 months.
My app worked very well.
I have done 1 month on Android side, because I fixed some bugs and added some features.

Today I have ported these mods on iOS side and now I have a NullReferenceException on Grid, when I scroll the List View. (On Android all works perfectly)

Here's what happens:
- I open the page that contains the list
- The list is loaded and displayed correctly
- If I try to scroll through the list, appears this exception

Stack Trace:

at Xamarin.Forms.Grid.CalculateAutoCells (System.Double width, System.Double height) [0x00357] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:144 at Xamarin.Forms.Grid.MeasureGrid (System.Double width, System.Double height, System.Boolean requestSize) [0x0000c] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:483 at Xamarin.Forms.Grid.LayoutChildren (System.Double x, System.Double y, System.Double width, System.Double height) [0x0000e] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:17 at Xamarin.Forms.Layout.UpdateChildrenLayout () [0x000c7] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:229 at Xamarin.Forms.Layout.OnSizeAllocated (System.Double width, System.Double height) [0x0000f] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:194 at Xamarin.Forms.VisualElement.SizeAllocated (System.Double width, System.Double height) [0x00000] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\VisualElement.cs:629 at Xamarin.Forms.Layout+<>c.<OnChildMeasureInvalidated>b__39_0 () [0x00080] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:332 at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/3969/44931ae8/source/xamarin-macios/src/Foundation/NSAction.cs:163 at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr) at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3969/44931ae8/source/xamarin-macios/src/UIKit/UIApplication.cs:79 at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3969/44931ae8/source/xamarin-macios/src/UIKit/UIApplication.cs:63 at MusiDownPortable.iOS.Application.Main (System.String[] args) [0x00008] in /Users/steebono/SourceTree/musidown/MusiDownPortable/MusiDownPortable/MusiDownPortable.iOS/Main.cs:17

Sometimes scroll works but when I try to reload list I have this exception:

Second StackTrace:

at Xamarin.Forms.Grid.GetLastAutoColumn (Xamarin.Forms.BindableObject child) [0x00016] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:657 at Xamarin.Forms.Grid.ExpandLastAutoColumnIfNeeded (System.Double width, System.Boolean expandToRequest) [0x00024] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:331 at Xamarin.Forms.Grid.MeasureGrid (System.Double width, System.Double height, System.Boolean requestSize) [0x0013a] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:520 at Xamarin.Forms.Grid.LayoutChildren (System.Double x, System.Double y, System.Double width, System.Double height) [0x0000e] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:17 at Xamarin.Forms.Layout.UpdateChildrenLayout () [0x000c7] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:229 at Xamarin.Forms.Layout.OnSizeAllocated (System.Double width, System.Double height) [0x0000f] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:194 at Xamarin.Forms.VisualElement.SizeAllocated (System.Double width, System.Double height) [0x00000] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\VisualElement.cs:629 at Xamarin.Forms.Layout+<>c.<OnChildMeasureInvalidated>b__39_0 () [0x00080] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\Layout.cs:332 at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/Foundation/NSAction.cs:163 at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr) at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:79 at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3969/7beaef43/source/xamarin-macios/src/UIKit/UIApplication.cs:63 at MusiDownPortable.iOS.Application.Main (System.String[] args) [0x00008] in /Users/steebono/SourceTree/musidown/MusiDownPortable/MusiDownPortable/MusiDownPortable.iOS/Main.cs:17

XAML Code:

<ListView x:Name="listView" ItemSelected="OnItemSelected" IsVisible="False" HasUnevenRows="False" RowHeight="50" IsPullToRefreshEnabled="True" Refreshing="mySongs_OnRefreshing"> <x:Arguments> <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy> </x:Arguments> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <ViewCell.ContextActions> <MenuItem Clicked="mySongDelete_OnClicked" CommandParameter="{Binding .}" Text="Delete" IsDestructive="True" /> </ViewCell.ContextActions> <Grid> <Grid.RowDefinitions> <RowDefinition Height="50" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="5" /> <ColumnDefinition Width="35" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="35" /> <ColumnDefinition Width="5" /> </Grid.ColumnDefinitions> <ff:CachedImage Source="{Binding FavoriteIcon}" CacheDuration="1" RetryCount="1" Aspect="AspectFit" HorizontalOptions="StartAndExpand" Grid.Row="0" Grid.Column="1"> <ff:CachedImage.GestureRecognizers> <TapGestureRecognizer Tapped="onClick_Favorite"/> </ff:CachedImage.GestureRecognizers> </ff:CachedImage> <Label Text="{Binding Title}" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" LineBreakMode="TailTruncation" FontSize="Medium" Grid.Row="0" Grid.Column="2" /> <ff:CachedImage Source="{Binding MenuIcon}" CacheDuration="1" RetryCount="1" Aspect="AspectFit" HorizontalOptions="EndAndExpand" Grid.Row="0" Grid.Column="3"> <ff:CachedImage.GestureRecognizers> <TapGestureRecognizer Tapped="onClick_Menu"/> </ff:CachedImage.GestureRecognizers> </ff:CachedImage> </Grid> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>

C# Code:

Inside OnAppearing():

`

// Other code here

listView.ItemSource = _myListItems;

// Other code here

`

My List is declared as:

`

private ObservableCollection<MyItemEntry> _myListItems = new ObservableCollection<MyItemEntry>();

`

MyItemEntry object is a class derived from INotifyPropertyChanged

I have an event that load and reload the list if needed:

`

        // Other code here

        // Start async operation
                Task.Run(() =>
                {
                    // Clear List
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        if (_myListItems.Any()) _myListItems.Clear();
                    });
                    // Get refreshed list.
                    var myList = DependencyService.Get<IItemHandler>().ReadItem;

                    if (myList.Any())
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            foreach (var itemDataEntry in myList)
                            {
                var menuIcon = "Menu100.png";
                                var favoriteIcon = itemDataEntry.Favorite ? "Favfill.png" : "Fav100.png";
                                _myListItems.Add(new MyItemEntry
                                {
                                    FavoriteIcon = favoriteIcon,
                                    MenuIcon = menuIcon,
                                    Title = decSong
                                });
                            }
                            if (_mySongsItems.Any())
                            {
                                Device.BeginInvokeOnMainThread(() =>
                                {
                                    listView.IsVisible = true;
                                    loadingIndicator.IsVisible = false;
                                    loadingIndicator.IsRunning = false;
                                    layoutDataInfo.IsVisible = false;
                                    lbDataInfo.IsVisible = false;
                                });
                            }
                            else
                            {
                                Device.BeginInvokeOnMainThread(() =>
                                {
                                    listView.IsVisible = false;
                                    loadingIndicator.IsVisible = false;
                                    loadingIndicator.IsRunning = false;
                                    layoutDataInfo.IsVisible = true;
                                    imgDataInfo.IsVisible = true;
                                    lbDataInfo.IsVisible = true;
                                });
                            }
                        });
                    }
                    else
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            listView.IsVisible = false;
                            loadingIndicator.IsVisible = false;
                            loadingIndicator.IsRunning = false;
                            layoutDataInfo.IsVisible = true;
                            imgDataInfo.IsVisible = true;
                            lbDataInfo.IsVisible = true;
                        });
                    }
                });

// Other code here for update list if needed

`

This codes on Android work perfectly. On iOS this codes work perfectly but if i try to scroll the list, I have that Exception.

A important thing is that this Event do not fire when I scroll the List.
I think that my code is not the cause of this Exception, because this happend only if I scroll
If I open the page and after do nothing, all work perfectly. I do not manage in any way scrolling or similar.

I have viewed the code of Xamarin Libraries and seems That Grid.ColumnDefinitions at some point became null.

First StackTrace say:

at Xamarin.Forms.Grid.CalculateAutoCells (System.Double width, System.Double height) [0x00357] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:144

In this line there is a for cycle:

for (var i = 0; i < _columns.Count; i++)

Second StackTrace say:

at Xamarin.Forms.Grid.CalculateAutoCells (System.Double width, System.Double height) [0x00357] in C:\BuildAgent2\work\ca3766cfc22354a1\Xamarin.Forms.Core\GridCalc.cs:657

In this line there is a if with same variable of first stacktrace:
if (_columns[i].Width.IsAuto)

so I think that the null reference exception is caused by _columns var.
As you can see in my xaml code I have set ColumnDefinitions.

This error happens when the list has already been created and displayed so.. someone set this to null at some point or Layout.UpdateChildrenLayout fails to get ColumnDefinitions value?

Another observation is that I set ItemSource of listView inside OnAppearing method; when I reload page, I clear my list object and I re-insert all updated items to list. But I think that this is not a problem because my list's items derived from INotifyPropertyChanged and my list is a ObservableCollecion list.

Xamarin Mac Env: last version iOS: 10.1 Xamarin Forms: 2.3.3.168 / 2.3.3.180 (Tried both)

Sorry for my english.

Thanks,
Stefano

Viewing all 91519 articles
Browse latest View live


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