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

Java.Lang.IllegalStateException....

$
0
0

I have an error that only showed up today. until yesterday it worked fine. in the meantime i have updated visual studio.
xamarin forms is 5.0
the error reports:
Java.Lang.IllegalStateException: 'The specified child already has a parent. You must call removeView () on the child's parent first. '

I have a scrollview which contains a variety of information (like whatsapp).

the information is contained in
public ObservableCollection <FlowNote> FlowNoteList {get {return Get <ObservableCollection <FlowNote>> (); } set {Set (value); OnPropertyChanged (); }}

when I delete an element it generates the error.

FlowNote fn = FlowNoteList.SingleOrDefault (Predicate => Predicate.IdNota == idnote);
FlowNoteList.Remove (fn);

except in case it is the last element ...

xaml è:

<ScrollView VerticalOptions="Start" Margin="0,0,0,50">
                <StackLayout x:Name="FlowStackLayout" VerticalOptions="Start">
                    <ListView x:Name="FlowListView" ItemsSource="{Binding FlowNoteList}" IsVisible="True" HasUnevenRows="True" SeparatorVisibility="Default">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>
                                    <SwipeView x:Name="swipView" SwipeStarted="SwipeView_SwipeStarted" SwipeEnded="SwipeView_SwipeEnded">
                                        <SwipeView.LeftItems>
                                            <SwipeItems>
                                                <SwipeItem Text="Share"
                                                   BackgroundColor="#2196F3"
                                                   Invoked="OnShareSwipeItemInvoked" >
                                                    <SwipeItem.IconImageSource>
                                                        <FontImageSource Color="Black" Size="15" FontFamily="UserIcons" Glyph="{Static models:FontIconsClass.Share}"></FontImageSource>
                                                    </SwipeItem.IconImageSource>
                                                </SwipeItem>
                                                <SwipeItem Text="Edit" IsVisible="{Binding isMe, Converter={StaticResource isMeBoolInvertConverter}}"
                                                   BackgroundColor="#2196F3"
                                                           Invoked="OnEditNoteSwipeItemInvoked" >
                                                    <SwipeItem.IconImageSource>
                                                        <FontImageSource Color="Black" Size="15" FontFamily="UserIcons" Glyph="{Static models:FontIconsClass.CommentEdit}"></FontImageSource>
                                                    </SwipeItem.IconImageSource>
                                                </SwipeItem>
                                            </SwipeItems>
                                        </SwipeView.LeftItems>
                                        <SwipeView.RightItems>
                                            <SwipeItems>
                                                <SwipeItem Text="Delete" IsVisible="{Binding isMe, Converter={StaticResource isMeBoolInvertConverter}}"
                                                   BackgroundColor="#2196F3"
                                                   Command="{Binding Path=BindingContext.UserDeleteNotaCommand, Source={x:Reference FlowStackLayout}}" CommandParameter="{Binding IdNota}" >
                                                    <SwipeItem.IconImageSource>
                                                        <FontImageSource Color="Red" Size="15" FontFamily="UserIcons" Glyph="{Static models:FontIconsClass.Delete}"></FontImageSource>
                                                    </SwipeItem.IconImageSource>
                                                </SwipeItem>
                                            </SwipeItems>
                                        </SwipeView.RightItems>

                                        <Grid>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="40"/>
                                                <ColumnDefinition Width="*"/>
                                                <ColumnDefinition Width="40"/>
                                            </Grid.ColumnDefinitions>

                                            <Frame Style="{Binding isMe, Converter={StaticResource IntToFrameChatBackgroundConverter}}" Grid.Column="{Binding isMe}" Margin="5" Grid.ColumnSpan="2" >
                                                <StackLayout Style="{Binding isMe, Converter={StaticResource IntToFrameChatBackgroundConverter}}" Grid.Column="{Binding isMe}" Margin="5" Grid.ColumnSpan="2" >
                                                    <Grid>
                                                        <Grid.ColumnDefinitions>
                                                            <ColumnDefinition/>
                                                            <ColumnDefinition/>
                                                            <ColumnDefinition Width="20"/>
                                                        </Grid.ColumnDefinitions>
                                                        <Label Text="{Binding User.Username}" TextColor="Black" IsVisible="{Binding isMe, Converter={StaticResource isMeBoolConverter}}" Margin="2" FontSize="12" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"/>
                                                        <Label Text="{Binding Data, StringFormat=' {0:dd-MMM-yy HH:mm}'}" Grid.Column="1" TextColor="Black" Margin="2" FontSize="12" HorizontalOptions="EndAndExpand" VerticalOptions="StartAndExpand"/>
                                                        <Image Grid.Column="2" HorizontalOptions="Center">
                                                            <Image.GestureRecognizers>
                                                                <TapGestureRecognizer Tapped="RowMenu_tapped" CommandParameter="{Binding PathDoc}" NumberOfTapsRequired="1"></TapGestureRecognizer>
                                                            </Image.GestureRecognizers>
                                                            <Image.Source>
                                                                <FontImageSource Color="Black" Size="25" FontFamily="UserIcons" Glyph="{Static models:FontIconsClass.DotsVertical}"></FontImageSource>
                                                            </Image.Source>
                                                        </Image>
                                                    </Grid>
                                                    <Label Text="{Binding Titolo}" TextColor="Black" IsVisible="{Binding Titolo, Converter={StaticResource StringNullOrEmptyBoolConverter}}" Margin="2" FontAttributes="Bold" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
                                                        <Label.GestureRecognizers>
                                                            <TapGestureRecognizer Tapped="OnTitoloTapped" NumberOfTapsRequired="2"/>
                                                        </Label.GestureRecognizers>
                                                    </Label>
                                                    <Label Text="{Binding Nota}" LineBreakMode="WordWrap" TextColor="Black" IsVisible="{Binding Nota, Converter={StaticResource StringNullOrEmptyBoolConverter}}" Margin="2" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
                                                        <Label.GestureRecognizers>
                                                            <TapGestureRecognizer Tapped="OnEditNoteTapped" NumberOfTapsRequired="2"/>
                                                        </Label.GestureRecognizers>
                                                    </Label>
                                                    <Image IsVisible="{Binding AllegatoList, Converter={StaticResource ObservableCollectionMultipleBoolConverter}}" HorizontalOptions="Start">
                                                        <Image.Source>
                                                            <FontImageSource Color="Black" Size="25" FontFamily="UserIcons" Glyph="{Static models:FontIconsClass.Attachment}"></FontImageSource>
                                                        </Image.Source>
                                                    </Image>
                                                    <StackLayout x:Name="BindableLayoutAllegati" BindableLayout.ItemsSource="{Binding AllegatoList}">
                                                        <!--https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/bindable-layouts-->
                                                        <BindableLayout.ItemTemplate>
                                                            <DataTemplate>
                                                                <StackLayout HorizontalOptions="CenterAndExpand">
                                                                    <Grid IsVisible="{Binding PathDoc, Converter={StaticResource IsAudioValueConverter}}" HeightRequest="60">
                                                                        <Grid.ColumnDefinitions>
                                                                            <ColumnDefinition Width="60"/>
                                                                            <ColumnDefinition Width="150"/>
                                                                            <ColumnDefinition Width="60"/>
                                                                        </Grid.ColumnDefinitions>
                                                                        <Image Source="{Binding Path=BindingContext.IconAudioPlayer, Source={x:Reference ImageAllegato}}" HeightRequest="50" WidthRequest="50" VerticalOptions="Center" HorizontalOptions="Center">
                                                                            <Image.GestureRecognizers>
                                                                                <TapGestureRecognizer Command="{Binding Path=BindingContext.PlayAudioCommand, Source={x:Reference ImageAllegato}}" CommandParameter="{Binding PathDoc}" NumberOfTapsRequired="1"></TapGestureRecognizer>
                                                                            </Image.GestureRecognizers>
                                                                        </Image>
                                                                        <StackLayout Grid.Column="1">
                                                                            <Label Text="{Binding TicksAudioPlayer}" TextColor="White" FontAttributes="Bold" HorizontalOptions="Center" />
                                                                            <Slider x:Name="SliderSongPlayDisplay" Value="{Binding PositionAudioPlayer}" HorizontalOptions="FillAndExpand" Minimum="0" Maximum="{Binding DurationAudioPlayer}" MinimumTrackColor="{StaticResource Primary}" ThumbColor="{StaticResource Primary}" />
                                                                        </StackLayout>
                                                                        <Image Grid.Column="2" Source="{Binding PathDoc, Converter={StaticResource URLtoThumbValueConverter}}" HorizontalOptions="Center"/>
                                                                    </Grid>
                                                                    <!--<Label Text="{Binding Thumb}"/>-->
                                                                    <!--<Image x:Name="ImageAllegato" Source="{Binding PathDoc, Converter={StaticResource URLtoThumbValueConverter}, ConverterParameter={Binding IsLinkWeb}}" HorizontalOptions="Center">-->
                                                                    <!--<Label Text="{Binding NomeDoc}" TextColor="Black" IsVisible="{Binding NomeDoc, Converter={StaticResource StringNullOrEmptyBoolConverter}}" Margin="2" FontAttributes="Bold" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"/>-->
                                                                    <Image x:Name="ImageAllegato" HorizontalOptions="Center">
                                                                        <Image.Source>
                                                                            <MultiBinding Converter="{StaticResource URLtoThumbMultiValueConverter}">
                                                                                <Binding Path="PathDoc" />
                                                                                <Binding Path="IsLinkWeb" />
                                                                                <Binding Path="Thumb" />
                                                                            </MultiBinding>
                                                                        </Image.Source>
                                                                        <Image.Triggers>
                                                                            <DataTrigger TargetType="Image" Binding="{Binding PathDoc, Converter={StaticResource IsAudioValueConverter}}" Value="True">
                                                                                <Setter Property="IsVisible" Value="False" />
                                                                            </DataTrigger>
                                                                        </Image.Triggers>
                                                                        <Image.GestureRecognizers>
                                                                            <TapGestureRecognizer Command="{Binding Path=BindingContext.ZoomPhotoCommand, Source={x:Reference ImageAllegato}}" CommandParameter="{Binding PathDoc}" NumberOfTapsRequired="2"></TapGestureRecognizer>
                                                                        </Image.GestureRecognizers>
                                                                    </Image>
                                                                    <Label Text="{Binding NoteDoc}" TextColor="Black" IsVisible="{Binding NoteDoc, Converter={StaticResource StringNullOrEmptyBoolConverter}}" Margin="2" FontAttributes="Bold" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand"/>
                                                                </StackLayout>
                                                            </DataTemplate>
                                                        </BindableLayout.ItemTemplate>
                                                    </StackLayout>
                                                </StackLayout>
                                            </Frame>
                                        </Grid>
                                    </SwipeView>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </StackLayout>
            </ScrollView>

(test on Android)

Thanks...


Is it possible to build a multi-language application using Forms?

$
0
0

I have been trying to follow a Microsoft tutorial shown here

And have got:

<Button x:Uid="Greeting" Text=""/>

And a resource file in my PCL with Greeting.Text with value Diary.. But I have nothing.

Is there a way to build a multi language application using Forms. Either using resources or config?

As a little more information. I don't really want to be adding a new string to WP, android and iOS every time. So would like this reosources file to be in the PCL. and would also like to bind to this file via XAML

How to capture fingerprint with UareU to database- xamarin.forms

$
0
0
I build a desktop app for my client which capture student's Bio data including fingerprint using U.are.U Digital persona. But now they want a mobile version of the same app. The question is how can I use U.are.U to capture fingerprint in xamarin.forms

Writing to Memo/Notes/OneNote

$
0
0

I'm writing a cross-platform app for Android/iOS/UWP.

I've got some text that I'm hoping I can store in the respective utility on each platform - Android = Memo, iOS = Notes, UWP = OneNote.

Can I do this with a regular StreamWriter, or is there something specific I need to do for each platform?

Xamarin.Forms CardsView nuget package

$
0
0

Hi all) I've released new package for Xamarin.Forms (Something like Tinder's CardsView)
Maybe, someone will be interested in it

nuget.org/packages/CardsView/ -- nuget
github.com/AndreiMisiukevich/CardView -- source and samples

QueryProperty changes string formatting

$
0
0

I am using QueryProperty to hand over a string from one page to the other. The string contains 2 backslashes like "\\TEST". When handed over to the other page it arrives as "/TEST". Is there any way to avoid this behaviour?

Xamarin Forms WebView CanGoBack == false

$
0
0

Hi, I have a very basic xaml page. Whole page is occupied by WebView element (in my case, its custom webview, but I didn't notice difference regarding this behavior). But WebView.CanGoBack are mostly returning false for some reason. I want user to navigate back to previous page when clicking hardware back, not navigating away from app. What am I missing?

My first thought was that page isn't fully loaded, and that's why WebView doesn't know that it can already navigate back. Tried to check it with Navigated – event raised when the page is loaded and navigation has stopped. But Navigated event is not called for every webpage as well. (I checked in ordinary browser, and back is working, links are changing)

Main issue - why GoBack isn't working as expected? And is there a way to check, that webpage is added to history stack? Or explicitly add webpage to stack?

In Xaml

<StackLayout>
        <local:HybridWebView x:Name="hybridWebView" 
                             VerticalOptions="FillAndExpand" 
                             HorizontalOptions="FillAndExpand" 
                             Navigated="hybridWebView_Navigated"
                             Uri="https://someexampleurl.com" />
    </StackLayout>

>

 protected override bool OnBackButtonPressed()
        {
            if (hybridWebView.CanGoBack)
            {
                hybridWebView.GoBack();
                return true;
            }
            else
            {
                return base.OnBackButtonPressed();
            }
        }

>

 public class HybridWebView : WebView
    {
        public static readonly BindableProperty UriProperty = BindableProperty.Create(
            propertyName: "Uri",
            returnType: typeof(string),
            declaringType: typeof(HybridWebView),
            defaultValue: default(string));

        public string Uri
        {
            get { return (string)GetValue(UriProperty); }
            set { SetValue(UriProperty, value); }
        }
    }

Xamarin.Forms: Restore some settings on reinstall/update app?

$
0
0

Hi All, What is the best way to re-load settings after app update or reinstall for Xamarin.Forms app. I am using Xamarin.Essentials > Preferences but I know they'll be lost on reinstall. There's no login/User Id on the app. What do you think is the best way of remembering on app updates?

(server upload with some unique id? local save options? what are my options.).

Thanks


ListView within a Listview

$
0
0

Hi,

I need to display multiple rows in each ListView ItemTemplate, for example I've database table with following records (FieldName: Value):

Config: 1, Colour: Blue
Config: 1, Size: M
Config: 2, Colour: Red
Config: 2, Size: L

And I want it to display like this (content between ______________ is ItemTemplate):


Colour - Blue
Size - M


Colour - Red
Size - L


It's almost like grouping (in this case by Config), but I don't want group headers and I also want ItemTeplate to be selectable. If I use grouping then I would get 4 rows instead of 2. I also don't need nested list to be scrollable.

Is this achievable in Xamarin Forms?

e.FirstVisibleItemIndex returns wrong position if collectionView contains Group

$
0
0

Hello team and hope doing well. I am trying to get e.FirstVisibleItemIndex inside a scrolled Event, using a collectionView with IsGrouped option to true.
Problem is that e.FirstVisibleItemIndex increases by one for each GroupHeader. I found a way which i can skip group header.

var index = e.FirstVisibleItemIndex;
            var categroyName = itemsList2[index].MainGroupItemName;
            var skipedIndex = mCategoryItems.ToList().FindIndex(x => x.MainGroupItemName == categroyName);
            var newIndex = index - skipedIndex;

Is there any more efficient way which i can get real index only from my items and not from groups

How to show tooltip in xamarin forms ?

$
0
0

My requirement is to show tooltips of button/controls on click on some next button.
Gone through the xamboy tootlip link, here on click of the same button showing tooltlip. But in my case I will click on some (Next) button and need to show tooltips of icons sequentially. It is like a app tour to show the first time user what the icons are meant for

OneSignal push notifications with custom sound

$
0
0

Hi everybody,

I'm using OneSignal for push notifications in Xamarin. everything works fine both at client side and onesignal REST API.

But i'm stuck at a point and cant find a solution. i cannot set a custom sound (a wav file) for notification.

I put the wav file into Assets folder in Project.Android, file is full lowercase (as described), set up the notification channel properties (as described). But noway, i still hear the default notification sound on the device. Im not sure but i think i put the wav files in wrong place. (thats not described in onesignal documentation)

Is there anyone who succeded at onesignal push notifications with custom sounds in Xamarin.Forms for android?

Regards.

Samsung galaxy watch - where is located my app in filesystem?

$
0
0

Hi,

I need to log my own message to simply .txt file, so I decided to do it this way:

    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "log.txt");

File.WriteAllText(filename, "test");

And I create log.txt in root of my app. When I open tizen device manager and connect to my watch, I see many of files and folders, but I cant find, where is located my app - rather - where is located my log.txt file to get access to this file?

EDIT:

I finally found it here: /home/owner/apps_rw/{my_app}/ but there is no log.txt, so I decided to put it on /shared/res/ folder. Now I see this file. I run my app - after run this should be write “test” word into this log txt file according this fileName path:

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "shared.res.log.txt");

no error appears, so I suppose, that it is working. Close my app, open device manager, locate my log.txt file - pull it into my computer, open and it is empty

CollectionView index crash

$
0
0

Hello everyone

I have an error with my code, that I can't figure out

I have a collectionView, and when I press "Editar mascota" and "Cancelar"

I get this error

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'

Note: I have a viewModel and I already supply the data to that collectionview with this view view Model

class MyMascotasViewModel : ViewModelBase {
        private ObservableCollection<Pet> _pets;
        public ObservableCollection<Pet> Pets {
            get {
                return _pets;
            }
            set {
                _pets = value;
                RaisePropertyChanged("Pets");
            }
        }

        IAuth auth;

        public MyMascotasViewModel() {
            Pets = new ObservableCollection<Pet>();

            auth = DependencyService.Get<IAuth>();

            GetData();
        }
        public async void GetData() {

            var document = await CrossCloudFirestore.Current
                                      .Instance
                                      .GetCollection("Pets")
                                      .WhereEqualsTo("Owner", auth.GetUserDisplayName())
                                      .GetDocumentsAsync();



            var p = document.ToObjects<Pet>();

            Pets.Clear();
            foreach (var item in p) {

                Pets.Add(item);
            }
        }
    }
}
 Pet p = e.CurrentSelection[0] as Pet;

            System.Diagnostics.Debug.WriteLine(e.CurrentSelection[0]);

            if (p != null) {
                string uid = string.Empty;
                string action = await DisplayActionSheet(null, null,
                          null, "¿Que desea ejecutar?", "Eliminar mascota", "Editar mascota", "Cancelar");

                switch (action) {

                    case "Eliminar mascota":
                        myMascotasViewModel.Pets.Remove(p);

                        var query = await CrossCloudFirestore.Current
                              .Instance
                              .GetCollection(Constants.PETS)
                              .WhereEqualsTo("Id", p.Id)
                              .GetDocumentsAsync();

                        foreach (var item in query.Documents) {
                            uid = item.Id;
                        }

                        await CrossCloudFirestore.Current
                                 .Instance
                                 .GetCollection(Constants.PETS)
                                 .GetDocument($"{uid}")
                                 .DeleteDocumentAsync();

                        break;
                    case "Editar mascota":
                        await Navigation.PushAsync(new EditPet(p));
                        ((CollectionView)sender).SelectedItem = null;
                        break;
                    default:
                        ((CollectionView)sender).SelectedItem = null;
                        break;
                }

Push notifications not working in xamarin forms.

$
0
0

I am working on xamarin forms. Where I am trying to send push notifications using google firebase and App center. Created one project on firebase and created one app on the App Center. Downloaded google-service.jon and pasted in the android project and configured server key with app center. After all the configuration I am trying to send push notification from the app center and changed manifest also as per documentation. But it is showing 0 sent

what could be the problem?


Ambiguous routes matched for

$
0
0

Hi
I have a Xamarin.forms project and I have defined my routing like this:

        Routing.RegisterRoute(nameof(HomePage), typeof(HomePage));
        Routing.RegisterRoute(nameof(BrowsePage), typeof(BrowsePage));
        Routing.RegisterRoute(nameof(NewItemPage), typeof(NewItemPage));
        Routing.RegisterRoute(nameof(BrowseByArtistPage), typeof(BrowseByArtistPage));
        Routing.RegisterRoute(nameof(LocationPage), typeof(LocationPage));
        Routing.RegisterRoute(nameof(PeoplePage), typeof(PeoplePage));
        Routing.RegisterRoute(nameof(HelpPage), typeof(HelpPage));
        Routing.RegisterRoute(nameof(AboutPage), typeof(AboutPage));

and this routing is being used in my flyout items
in my application the user can go from BrowseByArtistPage to another page BrowseByArtistPageDetail with

       BrowsePageArtistDetail browsePage = new BrowsePageArtistDetail();

        await Navigation.PushAsync(browsePage);

and from this page it goes to another page which is a tabbedpage with a similar code but when I call
Navigation.PopAsync I receive

Ambiguous routes matched for: //D_FAULT_FlyoutItem13/IMPL_BrowseByArtistPage/BrowseByArtistPage/D_FAULT_BrowsePageArtistDetail28 matches found: //D_FAULT_FlyoutItem13/IMPL_BrowseByArtistPage/BrowseByArtistPage/D_FAULT_BrowsePageArtistDetail28,//D_FAULT_FlyoutItem13/IMPL_BrowseByArtistPage/BrowseByArtistPage/D_FAULT_BrowsePageArtistDetail28
Parameter name: uri

in Navigation object which has a NavigationStack property I don't see any duplicated value , I don't know even what does this error means and where should I look to see this duplication
Any idea about how and where I can see this route stack that causes this error to happen
thanks

WebAuthenticator clarification please.

$
0
0

I apologize in advance for the lack of knowledge in this particular area, hence I am asking for directions that might help me to educate myself.

I am adjusting my xamarin app (forms and native droid and iOS) to work in the SSO environment. Naturally, I hoped to be able to use the Xamarin Essential's WebAuthenticator. Apparently, I might not truly understand all the intricacies of how SSO functions. This is not for the social (Google, FB, etc.) logins. It is for an SSO maintained by our client and I am working with them to get the specs and documentation. What I want to understand is what part of this needs to be done in the app and what needs to be done on a server?

My understanding is:
1) in the mobile app I basically call one method of the WebAuthenticator class. The browser will launch redirecting user to the SSO webpage. They enter credentials and the control return to my app. What does it mean for me, what do I get back upon successful login? Some sort of token? What do I do with it later? Currently the app works by calling APIs on our server to retrieve data and execute actions. Users are authenticated against our local database and JWT is used with each api call. How should it all change for the SSO case? Again, the SSO server and directory is hosted by our client, outside of our organization.

2) I believe, based on the limited documentation, there should be something added on our server side that will intercept the call from WebAuthenticator and redirect it to the outside SSO server. The server side of the system is handled by another team within our company that I work with, but I need to be able to direct them in what to do.

Any advice, help, suggestions, direction to learning resources (other than embarrassingly limited Microsoft documentation) is greatly appreciated.

Thank yo so much,
mike

Prism access BindingContext from code behind

$
0
0

Hi,

I need to dynamically build TableView from code behind as I can't achieve what I want with ListView (or any other component, complex scenario).

I'm trying to access BindingContext after InitializeComponent() in xaml.cs file, but BindingContext is not populated at this point as Prism Initialize method is not yet called in view model. In the Initialize method I'm accessing server and then populate view model.

viewModel = (SomeViewModel)this.BindingContext;

Tried both OnAppearing and OnBindingContextChanged event, still same issue. From what I understand Prism will call Initialize just before pushing the view, so there is no way to use BindingContext in code behind.

Is this not possible with Prism?

Accessing Resouces.resx strings within XAML forms?

$
0
0

I'm sure there has to be some simple thing I'm overlooking, but I want to try to access a string directly from the resx file in my forms project.

In the codebehind, this is super easy, but when implementing in xamarin.forms project, I cannot seem to access these strings. I'm trying to not have to code the string in the codebehind so I can just reuse the xaml code where needed.

Here is the code I am trying to execute.

szNoInventory is a label defined in the apps resx file.

    <Label 
    This is the line of code that I am trying to get to work.
                Text="{DynamicResource Key=szNoInventory}" />

I constantly get an error saying that szNoInventory cannot be found.

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 76418 articles
Browse latest View live