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

Real Modal Dialog with PRISM & RG.PopUp

$
0
0

I would like to achieve a functionality like an DisplayAlert with PRISM and RG.PopUp
PRISM and RG.PopUps works fine together and I know how to deal with NavigatedFrom, NavigatedTo and MessagingCenter to pass Answers back to my ViewModel. But I would like to wait for an answer and move forward afterwards, like in a DisplayAlert. I need just True or False.

if (await DialogService.DisplayAlertAsync("Question", "Yes or no ?, "Yes", "No") == false)
     return;

Something like this ( I made that up):

    var result = await NavigationService.NavigateAsync("PopUpYesNo", navigationParams);
    //now wait for PopUp to close
    if (result == true)
    {
    ...
    }

I can't be the first one looking for that, can I? I googled a lot but found nothing...


Button Design

$
0
0

Hey guys!
I want to give the buttons in my app a new color and found an example in the internet but I don´t know how to do it.

Hopefully you can help me!
Thanks in advance!

How to update properties between navigation pages?

$
0
0

I am trying to implement a basic login page that utilizes API configuration settings (API URL, SSL option, tenant ID) set on a settings content page. I currently have the two pages linked by the navigation API, with an icon in the Navigation.TitleView navigating the user to the settings page. I am attempting to use Xamarin.Essentials Preferences to store the configuration values. I tried to follow some tutorials on creating a BaseViewModel that implements the OnPropertyChanged interface and setting up properties in my ViewModels that call that event after the value has been set. I seem to be lost on how to get the StartPage to listen for and update it's properties when a preference value is updated on the SettingsPage. Currently it only updates after the application is restarted. Below is my code for my settings model and my ViewModels for my StartPage and SettingsPage. Assume there are text fields on the XAML pages that bind to the properties in the ViewModels.

ApplicationSettings Model

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Xamarin.Essentials;

namespace FieldServiceMobileApp.Models
{
    public static class ApplicationSettings
    {
        public static string Hostname
        {
            get
            {
                if(!Preferences.ContainsKey("Hostname"))
                {
                    Preferences.Set("Hostname", "");
                }

                return Preferences.Get("Hostname", "");
            }

            set => Preferences.Set("Hostname", value);
        }

        public static bool UseSSL
        {
            get
            {
                if (!Preferences.ContainsKey("UseSSL"))
                {
                    Preferences.Set("UseSSL", true);
                }

                return Preferences.Get("UseSSL", true);
            }

            set => Preferences.Set("UseSSL", value);
        }

        public static string ConfigGroup
        {
            get
            {
                if (!Preferences.ContainsKey("ConfigGroup"))
                {
                    Preferences.Set("ConfigGroup", "");
                }

                return Preferences.Get("ConfigGroup", "");
            }

            set => Preferences.Set("ConfigGroup", value);
        }

    }
}

StartPage ViewModel

using FieldServiceMobileApp.Models;
using FieldServiceMobileApp.Services;
using System.Collections.ObjectModel;
using Xamarin.Forms;

namespace FieldServiceMobileApp.ViewModels
{
    public class StartPageViewModel : BaseViewModel
    {
        public string Hostname
        {
            get => ApplicationSettings.Hostname;
            set
            {
                if (ApplicationSettings.Hostname == value)
                {
                    return;
                }

                ApplicationSettings.Hostname = value;
                OnPropertyChanged("Hostname");
            }
        }

        public bool UseSSL
        {
            get => ApplicationSettings.UseSSL;
            set
            {
                if (ApplicationSettings.UseSSL == value)
                {
                    return;
                }

                ApplicationSettings.UseSSL = value;
                OnPropertyChanged("UseSSL");
            }
        }

        public string ConfigGroup
        {
            get => ApplicationSettings.ConfigGroup;
            set
            {
                if (ApplicationSettings.ConfigGroup == value)
                {
                    return;
                }

                ApplicationSettings.ConfigGroup = value;
                OnPropertyChanged("ConfigGroup");
            }
        }

        // Observable collection for Mongoose Configurations:
        private ObservableCollection<MongooseConfiguration> _MongooseConfigurations;
        public ObservableCollection<MongooseConfiguration> MongooseConfigurations
        {
            get
            {
                return _MongooseConfigurations;
            }

            set
            {
                _MongooseConfigurations = value;
                OnPropertyChanged("MongooseConfigurations");
            }
        }

        // SelectedConfiguration Property:
        private MongooseConfiguration _SelectedConfiguration;
        public MongooseConfiguration SelectedConfiguration
        {
            get => _SelectedConfiguration;

            set
            {
                _SelectedConfiguration = value;
                OnPropertyChanged("SelectedConfiguration");
            }
        }

        // Username Property:
        private string _Username;
        public string Username
        {
            get => _Username;
            set
            {
                if (_Username == value)
                {
                    return;
                }

                _Username = value;
                OnPropertyChanged("Username");
            }
        }

        // Password Property:
        private string _Password;
        public string Password
        {
            get => _Password;
            set
            {
                if (_Password == value)
                {
                    return;
                }

                _Password = value;
                OnPropertyChanged("Password");
            }
        }

        public StartPageViewModel(iNavigationService FSMNavigationService) : base(FSMNavigationService)
        {

        }

        public override void Init()
        {
            Hostname = ApplicationSettings.Hostname;
            UseSSL = ApplicationSettings.UseSSL;
            ConfigGroup = ApplicationSettings.ConfigGroup;
        }

        public Command SettingsCommand => new Command(async () => await _FSMNavigationService.NavigateTo<SettingsViewModel>());
    }
}

SettingsPage ViewModel

using FieldServiceMobileApp.Models;
using System;
using FieldServiceMobileApp.Services;

namespace FieldServiceMobileApp.ViewModels
{
    public class SettingsViewModel : BaseViewModel
    {
        public string Hostname
        {
            get => ApplicationSettings.Hostname;
            set
            {
                if (ApplicationSettings.Hostname == value)
                {
                    return;
                }

                ApplicationSettings.Hostname = value;
                OnPropertyChanged("Hostname");
            }
        }

        public bool UseSSL
        {
            get => ApplicationSettings.UseSSL;
            set
            {
                if (ApplicationSettings.UseSSL == value)
                {
                    return;
                }

                ApplicationSettings.UseSSL = value;
                OnPropertyChanged("UseSSL");
            }
        }

        public string ConfigGroup
        {
            get => ApplicationSettings.ConfigGroup;
            set
            {
                if (ApplicationSettings.ConfigGroup == value)
                {
                    return;
                }

                ApplicationSettings.ConfigGroup = value;
                OnPropertyChanged("ConfigGroup");
            }
        }

        public SettingsViewModel(iNavigationService FSMNavigationService) : base(FSMNavigationService)
        {
            Hostname = ApplicationSettings.Hostname;
            UseSSL = ApplicationSettings.UseSSL;
            ConfigGroup = ApplicationSettings.ConfigGroup;
        }

        public override void Init()
        {

        }

    }
}

ListView with Switch ItemSelected toggle switch

$
0
0

Hey there,

I'm trying to toggle a switch inside a ListView it looks like this:

XAML behind:

<ContentPage.Content>

<ListView.ItemTemplate>



<Grid.ColumnDefinitions>



</Grid.ColumnDefinitions>
<Grid.RowDefinitions>

</Grid.RowDefinitions>


I implemented an observablecollection for that code is:

class Settings : INotifyPropertyChanged
    {
        private bool _toggled;
        public string name { get; set; }
        public string description { get; set; }
        public string image { get; set; }
        public string command { get; set; }
        public bool toggled { 
            get 
            { 
                return _toggled; 
            }
            set 
            {
                OnPropertyChanged(); _toggled = value;
            }
        }

        public Settings()
        {

        }

        public Settings(string name, string description, string image, string command, bool toggled)
        {
            this.toggled = toggled;
            this.name = name;
            this.description = description;
            this.image = image;
            this.command = command;
        }

        public Settings(string name, string description, string image, string command)
        {
            this.name = name;
            this.description = description;
            this.image = image;
            this.command = command;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

And in my Notification.xaml.cs there is just:

private System.Collections.ObjectModel.ObservableCollection<Model.Settings> setting = new System.Collections.ObjectModel.ObservableCollection<Model.Settings>();
        public NotificationSettings()
        {
            InitializeComponent();
            setting.Add(createSetting("General", "General subscribtion", "ring.png", "", true));
            lstSettings.ItemsSource = setting;
            LoadSettings();
        }

My item selected code is:

private async void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            if (null == e.SelectedItem || e.SelectedItemIndex == -1)
            {
                return;
            }
            Model.Settings item = (Model.Settings)e.SelectedItem;
            item.toggled = !item.toggled;
            ((ListView)sender).SelectedItem = null;


        }

My problem now is, that the first time I run start pressing the listview, the Switch isToggled value is updated, but the toggle itself not.
After that, the Switch keeps updating but the value of isToggled is always !item.toggled. So what am I doing wrong here?
Maybe is there a better way?

How to update item inside ObservableCollection

$
0
0

Hi all i have an ObservableCollection of model i want to change an item inside

public class MainModel
    {
        public int id { get; set; }
        public string name { get; set; }
        public string mainImage { get; set; }
        public Xamarin.Forms.Color textColor { get; set; }
    }

 public event PropertyChangedEventHandler PropertyChanged;

        public ObservableCollection<MainModel> _themes;

        public ObservableCollection<MainModel> themes
        {
            get { return _themes; }
            set
            {
                _themes = value;
                OnPropertyChanged("themes");
            }
        }

public ICommand changeColor
        {
            get
            {
                return new Command(() =>
                {
                    for(int i = 0; i < themes.Count; i++)
                    {
                        if (themes[i].id == Settings.categoryID)
                        {
                            themes[i].textColor = Xamarin.Forms.Color.FromHex("#eb1f8e");
                        }
                    }
                });
            }
        }

Can't authenticate MobileServiceClient with Azure ASP.NET Backend

$
0
0

Ciao,
I have ASP.NET Web Application (.NET Framework) based on Visual Studio 2019 template with custom authentication with individual user accounts.

 public void ConfigureAuth(IAppBuilder app)
    {
                // Configure the db context and user manager to use a single instance per request
                app.CreatePerOwinContext(ApplicationDbContext.Create);
                app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

                // Enable the application to use a cookie to store information for the signed in user
                // and to use a cookie to temporarily store information about a user logging in with a third party login provider
                app.UseCookieAuthentication(new CookieAuthenticationOptions());
                app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

                // Configure the application for OAuth based flow
                PublicClientId = "self";
                OAuthOptions = new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath = new PathString("/Token"),
                    Provider = new ApplicationOAuthProvider(PublicClientId),
                    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromDays(10),
                    // In production mode set AllowInsecureHttp = false
                    AllowInsecureHttp = false
                };

                // Enable the application to use bearer tokens to authenticate users
                app.UseOAuthBearerTokens(OAuthOptions);
    }

It works with Postman. I am able to obtain a token and access controller marked as [Authorize]

I am struggling with authentication of MobileServiceClient that I use for offline sync. Client is initialized in this way:

client = new MobileServiceClient(App.BackendUrl, new NativeMessageHandler());

     public async Task LoginAsync(string username, string password)
            {
                try
                {

                    var token = await GetAuthenticationToken(username, password);

                    MobileServiceUser user = new MobileServiceUser(token.userName);

                    user.MobileServiceAuthenticationToken = token.Access_Token;

                    client.CurrentUser = user;

                }
                catch (InvalidGrantException) 
                {
                    throw; 
                }
                catch (MobileServiceInvalidOperationException ex) 
                { 
                    throw; 
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                    Debug.WriteLine(ex);
                    throw;
                }
            }

        private async Task<AuthenticationToken> GetAuthenticationToken(string username, string password)
        {
            var keyValues = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("username", username),
                new KeyValuePair<string, string>("password", password),
                new KeyValuePair<string, string>("grant_type", "password")
            };

            HttpContent httpContent = new FormUrlEncodedContent(keyValues);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            try
            {

                var response = await client.InvokeApiAsync("/token",
                                        httpContent,
                                        HttpMethod.Post,
                                        null,
                                        null);

                return JsonConvert.DeserializeObject<AuthenticationToken>(await response.Content.ReadAsStringAsync());
            }
            catch (MobileServiceInvalidOperationException exception)
            {
                if (string.Equals(exception.Message, "invalid_grant"))
                    throw new InvalidGrantException("invalid credentials",  exception);
                else
                    throw;
            }
        } 

Here some code for testing:
public async Task InitializeAsync()
{
if (client?.SyncContext?.IsInitialized ?? false)
return;
// Create a reference to the local sqlite store
const string path = "syncstore.db";

            var store = new MobileServiceSQLiteStore(path);

            // Define the database schema
             store.DefineTable<Brand>(); brandTable = new AzureCloudTable<Brand>(client, null);

            // Actually create the store and update the schema
            try
            {
                await client.SyncContext.InitializeAsync(store);
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex);
                Debug.WriteLine(ex);
            }
        }

        async Task Test(string username, string password)
        {
            await LoginAsync("Simulator8", " ");
            await InitializeAsync();

            //Test pull
            try
            {
        await brandTable.PullAsync();
            }
            catch (Exception ex)
            {
            }
        }

Test throws exception:

  • ex {Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: The request could not be completed. (Unauthorized)
    at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient.ThrowInvalidResponse (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpResponseMessage response) [0x001d2] in :0
    at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient.SendRequestAsync (System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Boolean ensureResponseContent, System.Threading.CancellationToken cancellationToken) [0x00121] in :0
    at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient.RequestAsync (System.Boolean UseHandlers, System.Net.Http.HttpMethod method, System.String uriPathAndQuery, Microsoft.WindowsAzure.MobileServices.MobileServiceUser user, System.String content, System.Boolean ensureResponseContent, System.Collections.Generic.IDictionary2[TKey,TValue] requestHeaders, System.Threading.CancellationToken cancellationToken) [0x000f0] in <d385e67aff524dc7bd2d27425b9e81ae>:0 at Microsoft.WindowsAzure.MobileServices.MobileServiceTable.ReadAsync (System.String uriString, Microsoft.WindowsAzure.MobileServices.MobileServiceFeatures features) [0x0009c] in <d385e67aff524dc7bd2d27425b9e81ae>:0 at Microsoft.WindowsAzure.MobileServices.MobileServiceTable.ReadAsync (System.String query, System.Collections.Generic.IDictionary2[TKey,TValue] parameters, Microsoft.WindowsAzure.MobileServices.MobileServiceFeatures features) [0x00136] in :0
    at Microsoft.WindowsAzure.MobileServices.Sync.PullAction.ProcessTableAsync () [0x00134] in :0
    at Microsoft.WindowsAzure.MobileServices.Sync.TableAction.ExecuteAsync () [0x00251] in :0
    at Microsoft.WindowsAzure.MobileServices.Sync.MobileServiceSyncContext.ExecuteSyncAction (Microsoft.WindowsAzure.MobileServices.Sync.SyncAction action) [0x00090] in :0
    at Microsoft.WindowsAzure.MobileServices.Sync.MobileServiceSyncContext.PullAsync (System.String tableName, Microsoft.WindowsAzure.MobileServices.Sync.MobileServiceTableKind tableKind, System.String queryId, System.String query, Microsoft.WindowsAzure.MobileServices.MobileServiceRemoteTableOptions options, System.Collections.Generic.IDictionary2[TKey,TValue] parameters, System.Collections.Generic.IEnumerable1[T] relatedTables, Microsoft.WindowsAzure.MobileServices.MobileServiceObjectReader reader, System.Threading.CancellationToken cancellationToken, Microsoft.WindowsAzure.MobileServices.Sync.PullOptions pullOptions) [0x00361] in :0
  1. If I try token that I receive in token.Access_Token in Postman it works
  2. If I try sync with controller without [Authorize] it works.
  3. This is the message from Azure Log stream:

Username is correct. But if I don't call GetAuthenticationToken from LoginAsync and pass token manually to the user.MobileServiceAuthenticationToken then the result is:

So it seems that setting a user doesn't have any effect.

Any ideas why I can't authenticate my MobileServiceClient?

The specified child already has a parent. You must call removeView() on the child's parent first.

$
0
0

I am getting this exception when i try to reset the Application.Current.MainPage
I need to redirect the user whenever the app gets resumed.
to do so, I am trying to set the navigation page...

var mainPage = new NavigationPage(viewFactory.Resolve());
mainPage.BarBackgroundColor = Color.FromRgb(0, 130, 202);
mainPage.BarTextColor = Color.White;
_application.MainPage = mainPage;

But it throws error by saying Java.Lang.IllegalStateException: The specified child already has a parent. You must call removeView

The inner stack trace for the same is...

[0:] ERROR : System.Exception: Register ---> Java.Lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/jenkins/workspace/xamarin-android-d15-7/xamarin-android/external/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:152 
  at Java.Interop.JniEnvironment+InstanceMethods.CallNonvirtualVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniObjectReference type, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00089] in <7802aa64ad574c33adca332a3fa9706a>:0 
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0005d] in <7802aa64ad574c33adca332a3fa9706a>:0 
  at Android.Views.ViewGroup.AddView (Android.Views.View child) [0x00027] in /Users/builder/data/lanes/5945/dffc5912/source/monodroid/external/xamarin-android/src/Mono.Android/obj/Release/android-27/mcw/Android.Views.ViewGroup.cs:1920 
  at Xamarin.Forms.Platform.Android.NavigationRenderer.SwitchContentAsync (Xamarin.Forms.Page view, System.Boolean animated, System.Boolean removed) [0x002af] in D:\a\1\s\Xamarin.Forms.Platform.Android\Renderers\NavigationRenderer.cs:319 
  at Xamarin.Forms.Platform.Android.NavigationRenderer.OnPushAsync (Xamarin.Forms.Page view, System.Boolean animated) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.Android\Renderers\NavigationRenderer.cs:146 
  at Xamarin.Forms.Platform.Android.NavigationRenderer.PushViewAsync (Xamarin.Forms.Page page, System.Boolean animated) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.Android\Renderers\NavigationRenderer.cs:40 
  at Xamarin.Forms.Platform.Android.NavigationRenderer.OnElementChanged (Xamarin.Forms.Platform.Android.ElementChangedEventArgs`1[TElement] e) [0x000e8] in D:\a\1\s\Xamarin.Forms.Platform.Android\Renderers\NavigationRenderer.cs:118 
  at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].SetElement (TElement element) [0x000d5] in D:\a\1\s\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:178 
  at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement (Xamarin.Forms.VisualElement element) [0x00027] in D:\a\1\s\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:126 
  at Xamarin.Forms.Platform.Android.Platform.CreateRenderer (Xamarin.Forms.VisualElement element, Android.Content.Context context) [0x0001f] in D:\a\1\s\Xamarin.Forms.Platform.Android\Platform.cs:312 
  at Xamarin.Forms.Platform.Android.Platform.AddChild (Xamarin.Forms.VisualElement view, System.Boolean layout) [0x00009] in D:\a\1\s\Xamarin.Forms.Platform.Android\Platform.cs:570 
  at Xamarin.Forms.Platform.Android.Platform.SetPage (Xamarin.Forms.Page newRoot) [0x0007a] in D:\a\1\s\Xamarin.Forms.Platform.Android\Platform.cs:451 
  at Xamarin.Forms.Platform.Android.FormsApplicationActivity.InternalSetPage (Xamarin.Forms.Page page) [0x0001a] in D:\a\1\s\Xamarin.Forms.Platform.Android\FormsApplicationActivity.cs:245 
  at Xamarin.Forms.Platform.Android.FormsApplicationActivity.AppOnPropertyChanged (System.Object sender, System.ComponentModel.PropertyChangedEventArgs args) [0x00012] in D:\a\1\s\Xamarin.Forms.Platform.Android\FormsApplicationActivity.cs:233 
  at Xamarin.Forms.BindableObject.OnPropertyChanged (System.String propertyName) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:150 
  at Xamarin.Forms.Element.OnPropertyChanged (System.String propertyName) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\Element.cs:398 
  at Xamarin.Forms.Application.set_MainPage (Xamarin.Forms.Page value) [0x0008b] in D:\a\1\s\Xamarin.Forms.Core\Application.cs:98 
  at CondoControlCentralApp.Bootstrapper.Register () [0x00342] in C:\working\cccapp\CondoControlCentralApp\CondoControlCentralApp\Bootstrapper.cs:151 
   --- End of inner exception stack trace ---

Any idea, what I am doing wrong?

Thanks for the help

Want to show the 1st page of a TabbedPage OnResume() in iOS

$
0
0

When app started or resumed in Android I see the 1st page of a TabbedPage. But in iOS on resume it shows the last current page. I want to show the 1st page on resume also in iOS. Is it possible?


Open picker on Listview itemtapped event in xamarin forms

$
0
0

I want to Open picker list (picker.focus()) whenever I click on Frame.
I am using Xamarin forms with Prism Framework.

I have tried with below code but getting item object , not picker object.
<ListView.Behaviors>

                        <behavior:EventToCommandBehavior
                            EventName="ItemTapped"
                            Command="{Binding ApplyLeaveInfoCommand}"

                            EventArgsParameterPath="Item"/>

                    </ListView.Behaviors>

So Can I get picker.focus() after click on listview Item ???

Complete code:-


<ListView.ItemTemplate>





<Grid.RowDefinitions>


</Grid.RowDefinitions>
<Grid.ColumnDefinitions>


</Grid.ColumnDefinitions>

                                            <Image Source="{Binding ImageSource}" Aspect="AspectFit" Grid.Row="0" Grid.Column="1" Grid.RowSpan="2" VerticalOptions="CenterAndExpand" />
                                        </Grid><Frame.GestureRecognizers>
                                            <ClickGestureRecognizer Command="{Binding ApplyLeaveInfoCommand}"
                                                                    CommandParameter="{Binding .}"
                                                                    /></Frame.GestureRecognizers>
                        </Frame>
            </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>

MvvmCross Initializing IoC Throws MvxIoCResolveException

$
0
0

I've just upgraded an MvvmCross project from 6.3.1 to 6.4.1. One of the things this update did was change the return type of MvxFormsAndroidSetup.InitializeIoc() from void to IMvxIocProvider. So, to get the right return type, I re-wrote my method like this:

        protected override IMvxIoCProvider InitializeIoC()
        {
            base.InitializeIoC();

            var androidIoCContainer = Mvx.IoCProvider.CreateChildContainer();
            androidIoCContainer.RegisterSingleton(() => UserDialogs.Instance);
            androidIoCContainer.RegisterSingleton(() => CrossSettings.Current);
            androidIoCContainer.RegisterSingleton(() => CrossPermissions.Current);

            return androidIoCContainer;
        }

This builds, but throws an MvxIoCREsolveException on base.OnCreate() in MainActivity.cs: 'Failed to resolve type MvvmCross.Logging.IMvxLogProvider'.

Anyone know how to fix this? I'm guessing that by creating a ChildContainer in InitializeIoc(), I've created some conflict between different references to the IMvxLogProvider, but I'm still fairly new to MvvmCross, so I'm not sure how to proceed.

Here's the stack trace, if you're interested:

  at MvvmCross.IoC.MvxIoCContainer.Resolve (System.Type t) [0x0001c] in D:\a\1\s\MvvmCross\IoC\MvxIoCContainer.cs:252 
  at MvvmCross.IoC.MvxIoCContainer.Resolve[T] () [0x00000] in D:\a\1\s\MvvmCross\IoC\MvxIoCContainer.cs:242 
  at MvvmCross.IoC.MvxIoCProvider.Resolve[T] () [0x00000] in D:\a\1\s\MvvmCross\IoC\MvxIoCProvider.cs:66 
  at MvvmCross.Core.MvxSetup.CreateLogProvider () [0x00000] in D:\a\1\s\MvvmCross\Core\MvxSetup.cs:329 
  at MvvmCross.Core.MvxSetup.InitializeLoggingServices () [0x00000] in D:\a\1\s\MvvmCross\Core\MvxSetup.cs:277 
  at MvvmCross.Core.MvxSetup.InitializePrimary () [0x0002f] in D:\a\1\s\MvvmCross\Core\MvxSetup.cs:79 
  at MvvmCross.Core.MvxSetupSingleton.StartSetupInitialization () [0x0000a] in D:\a\1\s\MvvmCross\Core\MvxSetupSingleton.cs:181 
  at MvvmCross.Core.MvxSetupSingleton.EnsureInitialized () [0x00017] in D:\a\1\s\MvvmCross\Core\MvxSetupSingleton.cs:102 
  at MvvmCross.Forms.Platforms.Android.Views.MvxFormsAppCompatActivity.OnCreate (Android.OS.Bundle bundle) [0x0000c] in D:\a\1\s\MvvmCross.Forms\Platforms\Android\Views\MvxFormsAppCompatActivity.cs:105 
  at SDA.Droid.MainActivity.OnCreate (Android.OS.Bundle bundle) [0x00017] in C:\Users\shodg\SDA\SDA\SDA.Android\MainActivity.cs:17 
  at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x00011] in <4ccdb3137d974856b786e1aeebbfbab6>:0 
  at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.17(intptr,intptr,intptr)

How can I hide or bloCk the master detail page when I'm in one of the pages of the menu?

$
0
0

I mean, I got a master Detail which contains Sells, Stock, Buys, Etc.. and when you select "Stock" you go to the stock page, but the menu still appears if you slide the screen from left to right, I don't wanna that happen, I could hide the three menu lines from the navigation page bar but still appears if you slide it, How can I block that action?

How to connect MySql and Xamarin.Forms?

$
0
0

I have a task: make a connection between Xamarin.Android and MySql DB, wich is located on db4free.net

Everything works for PC, but for Android there is an exeception:

Why is it so?

the code is:

        string myConnectionString = "Server=www.db4free.net;Port=3306;User Id=****;Password=****;Database=****;OldGuids=True";
        MySqlConnection connection = new MySqlConnection(myConnectionString);
        connection.Open();
        ....

Emulator stopped working

$
0
0

I added an image to my app (visual studio 2019) and somehow this broke my emulator. Every time I try to run it it either will stop or it will crash my laptop. It worked just a day ago though, and even when I remove the image it still won't run. Other apps won't run either. I've gotten an error saying that I haven't added the correct ABI's to run an x86 emulator, yet when I try to change emulator processors they still will not work. I've also gotten this error message:

emulator: WARNING: UpdateCheck: Failure: Couldn't resolve host name.

What is going on here and how can I get my emulator to run again?

Adding Embedded Image Using Markup Extension/assembly for ContentProperty?

$
0
0

Hi Guys,

I'm using VS2019 on a Mac. Adding my first embedded image. My compiler has a big red line under the [ContentProperty? It says I'm missing an assembly or something? Under Add/Reference I added System.Xaml.dll (there were like 7 versions on the system?) but still no joy. I appreciate any help you can give me!

Thanks,
Brett

Error when building is -
/Users/davis/Projects/MyImageApp/MyImageApp/ImageResourceExtension.cs(6,6): Error CS0246: The type or namespace name 'ContentPropertyAttribute' could not be found (are you missing a using directive or an assembly reference?) (CS0246) (MyImageApp)

My code -

using System;
using System.Reflection;
using Xamarin.Forms.Xaml;

namespace MyImageApp
{
[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
public string Source { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Source == null)
        {
            return null;
        }

        // Do your translation lookup here, using whatever method you require
        var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);

        return imageSource;
    }
}

}

Scroll in listView

$
0
0

Hi,

I have a listView where the number of items depends on someones input. In some cases, there are not many items so all items in the list are visible. In other cases however, the number of items exceeds the limit of list items to be seen, so the user should be able to Scroll the list to see every item.

Adding the code here does not seem to work..

Thus two questions:

  • How to scroll in a listView (including a scrollbar)? I can't figure out how to do that.
  • Is it possible that the scrolling and scrollbar will only be enabled when there are too many list items?

I hope someone can help.

Regards, Ganesh


Set and get element by name in code behind or maybe another suggestion

$
0
0

So i have a List of MyModel which has hierarchical structure.

public class MyModel{
public int Id { get; set; }
public string Name{ get; set; }
public int ParentId{ get; set; }
}

I wanted to a create a simple hierarchical layout. So i used this method.

        private void CreateLayoutsHierarchical(List<MyModel> myModelList)
        {
            Dictionary<int, StackLayout> dict = new Dictionary<int, StackLayout>();
            dict.Add(0, RootLayout); //RootLayout is an empty stack layout in the xaml

            foreach (MyModel myModel in myModelList)
            {
                StackLayout parentLayout = null;
                dict.TryGetValue(myModel.ParentId, out parentLayout);

                StackLayout sL = new StackLayout();
                sL.Orientation = StackOrientation.Vertical;
                Label label = new Label();
                label.Text = myModel.Name;

                sL.Children.Add(label);
                dict.Add(myModel.Id, sL);

                parentLayout.Children.Add(sL);
            }

Well it worked but can i do this differently? Hopefully not using a dictionary? I tried setting and getting elements names(maybe HLayout1, HLayout2,..) in code but is that possible? I couldnt do it?

Scanning App in Xamarin forms using custom renderer

$
0
0

I have to implement a Scanning App in Xamarin forms. I want to use AVFoundation for iOS Google Vision for Android. can you please tell me how to achieve it. I tried ZXing but It is creating issue with some of the QRcode, if it is complex of not clear.

What analytics tools do y'all use?

$
0
0

I am currently only using Appcenter, but curious to hear what folks are using as Analytics tools for Xamarin. Appcenter is a little clunky and doesn't really show analytics data well. Looking for engagement information primarily and demographic data.

How to change the Navigation Page Title font in UWP?

$
0
0

I am trying to use a custom font for my Navigation Page Titles.

I have scratched out the unwanted details. I want to use a custom font for the Navigation Bar title, that reads - "Page Title".
I was able to customize the the tabbed page titles by adding a fontfamily to the TextBlock in PivotStyle.

Is there anyway of writing a similar style for Navigation Page? I am fairly new to UWP and this is my first application.
Also it'll be very helpful if you can even help me with customizing that thin horizontal blue line under the "Tab 1", and disable hover action for the Hamburger menu icon.

So, I am trying to find a solution to 3 problems:
1. Custom fonts for navigation bar title.
2. Change the Tabbed bar, selection color.(The thin blue line)
3. Disable hover action on the Hamburger menu icon.

It is really difficult to find any kind of resource for Xamarin.UWP. Please help. Thanks in advance :smiley:

Not able to override AppBarButtonStyle

$
0
0

So, far I have had major luck in overriding PaneButtonStyle and some single style setters for TextBlocks and SolidColorBrush. The trick is to just redefine them in App.Xaml with the same x:key as the original style. Now, I tried the same with AppBarButtonStyle with this: https://stackoverflow.com/a/55470551.

Is there a way to override it with a custom renderer as well, like done here: https://forums.xamarin.com/discussion/151174/can-not-override-pivotheaderitem-uwp#latest, for TabbedPageStyle??

Viewing all 81910 articles
Browse latest View live


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