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

Cutting Corners ---- possibly a frame bug?

$
0
0

Hi. I am having some trouble with borders. I want a gold border around my page and I want it to be 2 pixels thick.

I originally did this with:

[frame bordercolor='gold' cornerradius='12']
[frame bordercolor='gold' cornerradius='12']
[stacklayout] .............

However the inner frame would be cut off slightly, so I then tried:

[frame backgroundcolor='gold' padding='2' cornerradius='12']
[stacklayout]..........

However, now the sharp corned stacklayout cuts all the way through the frame.

So... a frame does not really seem to be a frame for making borders.

How can I get a rounded 2 pixel frame all the way around my stacklayout without the corners being cut into by the stacklayout? ie. I want to stacklayout to honor the 2 pixel padding at the rounded corners of the frame. I also tried adding IsClippedToBounds="True" to the StackLayout, but that made no difference.

Thank you.


Custom pin with additional properties not diplaying

$
0
0

My assumption is if i have a CustomPin as below

 public class CustomPin : Pin
{
   public string Name {get; set;}
   public string Url {get; set;}
}

and you set it in your pin as below

CustomPin pin = new CustomPin
                {
                    Type = PinType.Place,
                    Position = new Position(111, 222),
                    Label = "XXXXXXXXXXXXX",
                    Address = "XXXXXXX",
                    Name = "Xamarin",
                    Url = "http://xamarin.com/about/"
                };

Then the name and address "should" display when you click the pin? Is that correct? As looking at this sample it doesnt seem to be the case?

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/map-pin

Xamarin.Form data security

$
0
0

I am going to develop xamarin form app for both iOS and android. This app should not have login function and I want to keep the app data securely to prevent from reverse engineering. I would like to know how and where to keep the data securely.

I found these 2 approaches.

First approach

  • Consume data from API using Token and save data in sqlite database and then encrypt it. With this approach my first question is where to store the token securely? Should the whole database be encrypted using SQChiper or should only sensitive column be encrypted in term of performance and security? The data size is about more or less 1MB.

Second approach

  • Embedded the encrypted sqlite database in the app and decrypt it in the app. Again, the question is where to store the key securely to perform decryption of the data?

Both are not completely secure. Do you have a better way to implement this scenario.

Xamarin.Forms Binding Nullable double to Entry

$
0
0

Hello everyone,

I'm trying to bind a nullable double to an Entry like this :

private double? nicotineRate; public double? NicotineRate { get { return nicotineRate; } set { nicotineRate = value; SetProperty(ref nicotineRate, value); } }

<Entry Placeholder="Nicotine rate" Text="{Binding NicotineRate}" Keyboard="Numeric" HorizontalTextAlignment="Center"></Entry>

But i'm not able to obtains a value on my "NicotineRate" property.

I think it's because Xamarin.Forms does not bind those controls to nullable values. Is it possible to do this with the help of a custom renderer, or a converter ?

My need is to provide a form with empty entries with visible placeholders at initialization, this is why i need to bind to nullable values.

Thank you !

how to create header bar with buttons for all pages including backbutton

$
0
0

I have created a header using a control template including some buttons.

  1. How to handle button event in app.xaml
  2. Each button clicks redirect to a specific page
  3. I need to add back button for getting the previous page

Xamrin form issue with HTTPS request

$
0
0

I have created an application in Xamrin forms with Visual studio 2017 Professional and Visual studio 2019 cumulative addition.

Problem is that app works fine with HTTP request, but in case of HTTPS request i have got time out every time with visual studio 2017 & with visual studio 2019 i have observed sometime getting response of request and sometime app not able to hit HTTPS request.

I have same code to call API. I am able to post WEB API with Postman every time successfully.

        HttpStatusCode = HttpStatusCode.Unused;
        HttpStatusCodeDescription = String.Empty;

        var response = default(TResp);
        XStatusCode = null;

        HttpWebRequest webRequest = null;
        HttpWebResponse webResponse = null;

        webRequest = (HttpWebRequest)WebRequest.Create(mServiceUrl + serviceName);

        webRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password)));

        webRequest.Method = "POST";



        var reqData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request));

        webRequest.ContentLength = reqData.Length;
        webRequest.ContentType = "application/json; charset=utf-8";
         using (var reqStream = webRequest.GetRequestStream())
            reqStream.Write(reqData, 0, reqData.Length);

        try
        {
            using (webResponse = (HttpWebResponse)webRequest.GetResponse())
            {
                if (typeof(TResp) != typeof(object))
                {
                    using (var respStream = webResponse.GetResponseStream())
                    {
                        var reader = new StreamReader(respStream);
                        string result = reader.ReadToEnd();
                        response = JsonConvert.DeserializeObject<TResp>(result);
                    }
                }

                HttpStatusCode = webResponse.StatusCode;
                HttpStatusCodeDescription = webResponse.StatusDescription;
            }
        }
        catch (WebException ex)
        {
            webResponse = (HttpWebResponse)ex.Response;
            if (webResponse != null)
            {
                HttpStatusCode = ((HttpWebResponse)webResponse).StatusCode;
                HttpStatusCodeDescription = ((HttpWebResponse)webResponse).StatusDescription;
                if (webResponse.Headers["X-StatusCode"] != null)
                {
                    XStatusCode = int.Parse(webResponse.Headers["X-StatusCode"]);
                    if (webResponse.ContentLength > 0)
                    {
                        if (typeof(TResp) != typeof(object))
                        {
                            using (var respStream = webResponse.GetResponseStream())
                            {
                                var reader = new StreamReader(respStream);
                                string result = reader.ReadToEnd();
                                response = JsonConvert.DeserializeObject<TResp>(result);
                            }
                        }
                    }
                }
                webResponse.Close();
            }
        }

        return response;

Tried out with Http Client also getting same result

HttpStatusCode = HttpStatusCode.Unused;
HttpStatusCodeDescription = String.Empty;

        var result = default(TResp);
        XStatusCode = null;




        try
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password)));

            var json = JsonConvert.SerializeObject(request);
            HttpContent content = new StringContent(json);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var response = await client.PostAsync(mServiceUrl + serviceName, content);


            if (response.IsSuccessStatusCode)
            {
                result = JsonConvert.DeserializeObject<TResp>(response.Content.ToString());
            }

        }
        catch (WebException ex)
        {
            var webResponse = (HttpWebResponse)ex.Response;
            if (webResponse != null)
            {
                HttpStatusCode = ((HttpWebResponse)webResponse).StatusCode;
                HttpStatusCodeDescription = ((HttpWebResponse)webResponse).StatusDescription;
                if (webResponse.Headers["X-StatusCode"] != null)
                {
                    XStatusCode = int.Parse(webResponse.Headers["X-StatusCode"]);
                    if (webResponse.ContentLength > 0)
                    {
                        if (typeof(TResp) != typeof(object))
                        {
                            using (var respStream = webResponse.GetResponseStream())
                            {
                                var reader = new StreamReader(respStream);
                                string resulttmp = reader.ReadToEnd();
                                result = JsonConvert.DeserializeObject<TResp>(resulttmp);
                            }
                        }
                    }
                }
                webResponse.Close();
            }
        }



        return result;

PCL package

Android package

Help with setting info window with custom pins and image

$
0
0

``I have added the below class to my Android Project

public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
    {
        //private List<CustomPin> _customPins = new List<CustomPin>();
        public CustomMapRenderer(Context context) : base(context)
        {
        }

        protected override void OnMapReady(GoogleMap map)
        {
            base.OnMapReady(map);

            NativeMap.SetInfoWindowAdapter(this);
        }

        // If you want to customize the pin itself
        protected override MarkerOptions CreateMarker(Pin pin)
        {
            var marker = base.CreateMarker(pin);
            //_customPins.Add(((CustomPin)pin)); // Not sure if i should assign this here

            if (pin is CustomPin customPin)
            {
                marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
                marker.SetTitle(pin.Label);
                marker.SetSnippet(pin.Address);

                marker.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueGreen));
            }

            return marker;
        }

        // To customize the info window
        // Follow the guide
        //private void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
        //{
        //    var customPin = GetCustomPin(e.Marker);
        //    if (customPin == null)
        //    {
        //        throw new Exception("Custom pin not found");
        //    }

        //    if (!string.IsNullOrWhiteSpace(customPin.Url))
        //    {
        //        var url = Android.Net.Uri.Parse(customPin.Url);
        //        var intent = new Intent(Intent.ActionView, url);
        //        intent.AddFlags(ActivityFlags.NewTask);
        //        Android.App.Application.Context.StartActivity(intent);
        //    }
        //}

        public Android.Views.View GetInfoContents(Marker marker)
        {
            var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
            if (inflater != null)
            {
                Android.Views.View view;

                var customPin = GetCustomPin(marker);
                if (customPin == null)
                {
                    throw new Exception("Custom pin not found");
                }

                if (customPin.Name.Equals("Xamarin"))
                {
                    view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null); // XamarinMapInfoWindow Does NOT exist anywhere, same with other extensions below
                }
                else
                {
                    view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
                }

                var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
                var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);

                if (infoTitle != null)
                {
                    infoTitle.Text = marker.Title;
                }
                if (infoSubtitle != null)
                {
                    infoSubtitle.Text = marker.Snippet;
                }

                return view;
            }
            return null;
        }

        public Android.Views.View GetInfoWindow(Marker marker)
        {
            //CustomPin GetCustomPin(Marker annotation)
            //{

            //    var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
            //foreach (var pin in _customPins) // customPins does not exist
            //{
            //    if (pin.Position == position)
            //    {
            //        return pin;
            //    }
            //}
            //}
            return null;
        }

    }

Im struggling to get this working and have been reading the documentation but something or another doesnt work or i get another error message. Ive put some comments on my code above where i have some issues. I cant find any namespace that needs to be imported so it makes me think im doing something wrong.

Front end declaration is

    <ContentPage.Content>
        <views:CustomMap x:Name="customMap" MapType="Street"/>
    </ContentPage.Content>

I have a class that attaches to the above Class in my Android project

    public class CustomMap : Map
    {
        public List<CustomPin> CustomPins { get; set; }
    }

public class CustomPin : Pin
{
    public string Name { get; set; }
    public string Url { get; set; }
    public string CustomImage {get; set;}
}

I followed the documentation to set the above but missing certain stuff i assume or the documentation isnt very clear to me.

In short i would like to show the customPin properties along with the Label and Address in a pop up when the user clicks an icon.
The second thing im attempting to achieve is to have a custom icon for the pins and again everything i try either doesnt work or i get a Java error stating to use a bitmap.

Would appreciate if someone could show me an example as all the ones i have seen either dont work or show up as deprecated/obsolete or doesnt exist with the code im using.

Thanks

Shell showing Modal pages

$
0
0

I would like to use modal pages the same as I use GoToAsync("modalpage?parameter=somevalue") navigation. Is this possible?


Cheap android devices to test with

$
0
0
So to test in app purchases I need a real device from what I read. What are good cheaper devices to test with?

How to call an azure function in a secure way

$
0
0

We have a list of azure functions that we would like to call from the xamarin forms app.(user should not be prompted a login,all silent calls)

Functions have AuthorizationLevel=Function and therefore requires a function Key.

Where do you store the functionKey? definetely not in the app, I have read that the vault is not the way to do it.

How do you do it? is SAS the way to do it? or vault?
cannot find anything as guidance

any suggestions

Crashlog

$
0
0

Hello Everyone!

I am getting a crash on iOS and am having trouble finding out the source of the crash. Since I am not that used to reading crashlogs I thought I would ask here :)

The crash occurs only on iOS and happens the second time that you put the app to sleep.

Can anyone make help me to make sense of the crashlog?

Can't catch exceptions from HttpWebRequest after Xamarin update

$
0
0

Hi,

I recently updated everything in my Visual Studio Mac installation. I still use Xamarin Forms 3.1 though.

After this update, I have got a lot of crashes from Android users (I haven't released the iOS version yet) and it seems to be related to HttpWebRequest. I use it in the following way:

        WebRequest req = HttpWebRequest.CreateDefault(new Uri(url));
        req.Timeout = TimeoutMilis;
        ...
        using (Stream dataStream = req.GetRequestStream())
        {
            dataStream.Write(data, 0, data.Length);
        }

I have a try catch around it, but it seems like these errors are not caught. The stack traces I get are not very helpful either:

        android.runtime.JavaProxyThrowable: System.AggregateException: A Tasks exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.Net.WebException: The request was aborted: The request was canceled. 

        caused.AggregateException(s)
        System.Net.HttpWebRequest.<MyGetResponseAsync>d__243.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        --- End of inner exception stack trace ---
        ---> (Inner Exception #0) System.Net.WebException: The request was aborted: The request was canceled.
        System.Net.HttpWebRequest.<MyGetResponseAsync>d__243.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0

Another similar crash:

         android.runtime.JavaProxyThrowable: System.AggregateException: A Tasks exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.ObjectDisposedException: Cannot access a disposed object. 

        caused.AggregateException(s)
        Object name: 'System.Net.Sockets.Socket'.
        System.Net.Sockets.Socket.ThrowIfDisposedAndClosed()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.Sockets.SocketTaskExtensions.<>c.<ConnectAsync>b__2_1(IAsyncResult asyncResult)<1430f9cebba746309b69090b6cda9ce8>:0
        System.Threading.Tasks.TaskFactory<TResult>.FromAsyncCoreLogic(IAsyncResult iar, Func<T, TResult> endFunction, Action<T> endAction, Task<TResult> promise, bool requiresSynchronization)<e7c4dd6cd0ad467d9712102a6791959b>:0
        System.Net.WebConnection.<Connect>d__16.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebConnection.<InitConnection>d__19.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebOperation.<Run>d__57.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebCompletionSource<T>.<WaitForCompletion>d__15.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebOperation.<GetRequestStream>d__49.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        --- End of inner exception stack trace ---
        ---> (Inner Exception #0) System.ObjectDisposedException: Cannot access a disposed object.
        Object name: 'System.Net.Sockets.Socket'.
        System.Net.Sockets.Socket.ThrowIfDisposedAndClosed()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.Sockets.SocketTaskExtensions.<>c.<ConnectAsync>b__2_1(IAsyncResult asyncResult)<1430f9cebba746309b69090b6cda9ce8>:0
        System.Threading.Tasks.TaskFactory<TResult>.FromAsyncCoreLogic(IAsyncResult iar, Func<T, TResult> endFunction, Action<T> endAction, Task<TResult> promise, bool requiresSynchronization)<e7c4dd6cd0ad467d9712102a6791959b>:0
        System.Net.WebConnection.<Connect>d__16.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebConnection.<InitConnection>d__19.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebOperation.<Run>d__57.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebCompletionSource<T>.<WaitForCompletion>d__15.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0
        System.Net.WebOperation.<GetRequestStream>d__49.MoveNext()<1430f9cebba746309b69090b6cda9ce8>:0

Has anyone had a similar problem?

Does anyone know how to create pdf from base64 string and show in xamarin forms ?

$
0
0

Hi all,

Does anyone know how to display base64 string to webview in Xamarin forms and then I need to download this base64 string in pdf file.

How to bind two elements to a control and use one of them?

$
0
0

I have a ListView that displays a collection of open orders, through this same ListView I want to display the same collection of only closed orders. I could make two ListView, which on command enabled and disabled, tell me how to do it correctly.

<ListView ItemsSource="{Binding Deliveries}" SeparatorVisibility="None" HorizontalOptions="FillAndExpand" VerticalOptions="Start" HasUnevenRows = "true"> <ListView.Behaviors> <prism:EventToCommandBehavior EventName="ItemTapped" Command="{Binding DeliveryTappedCommand}" EventArgsConverter="{StaticResource deliveryTappedEventArgsConverter}"/> </ListView.Behaviors> <ListView.ItemTemplate> <DataTemplate > </ListView>

Hi I want to convert entire Xamarin form in PDF . Is there any way to do this?

$
0
0

Hi I want to convert entire Xamarin form in PDF . Is there any way to do this without any third party paid library .

I have got a solution using syncfusion but this is not opensource .


Xamarin Forms Android error CS0117: 'Resource.Drawable' does not contain a definition for “…”

$
0
0

I am trying to build a splash screen with a video in Xamarin Forms Android on Visual Studio 2019. Xamarin Forms version 4.7.0.968. I am trying to open a video file "Intro.mp4" located in the Resources/drawable folder. The video's build action is set to "AndroidAsset" and it already contains an id in Resource.designer.cs inside the Drawable class:

Here's where I am referencing the file:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate(savedInstanceState);

    StartService(new Android.Content.Intent(this, typeof(AudioService)));

    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

    SetContentView(Resource.Layout.Splash);
    var videoView = FindViewById<VideoView>(Resource.Id.splashVideo);

    string videoPath = $"android.resource://{Application.PackageName}/{Resource.Drawable.Intro}";
    videoView.SetVideoPath(videoPath);
    videoView.Start();            

    LoadApplication(new App());
}

When I build the project I get this error: "error CS0117: 'Resource.Drawable' does not contain a definition for 'Intro'". I tried several suggestions I found in the forums, delete the obj and bin folders, restart Visual Studio, restart my pc, uninstall Xamarin and reinstall it, roll back to the previous Xamarin packages in NuGet Package Manager but nothing is helping. I am not sure if it's a Xamarin bug or an issue with my code. Any help will be much appreciated.

AWS S3 Object Permissions when saved a file using PutObject() in an Xamarin.Forms app

$
0
0

When I save to a file using PutObject(), the file becomes private. So subsequent reads are denied access. How do I make it public?

My code is:

                    PutObjectRequest request = new PutObjectRequest
                    {
                        BucketName = EntBucketName.Text.Trim(),
                        Key = FileName.Text.Trim(),
                        ContentBody = FileContents.Text.Trim(),
                        //CannedACL = S3CannedACL.PublicReadWrite,
                    };

                    PutObjectResponse response = await App.awsS3Client.PutObjectAsync(request);

When I set CannedACL property, the PutObject fails with 'Access Denied' exception. When that is not included the file is overwritten but becomes private so subsequent GetObject fails.

Deleting the file and then saving to it also didn't help.

Preventing hardware back button from bypassing form validation with Xamarin Forms/ Prism/ MVVM

$
0
0

I'm a newbie to Xamarin Forms and Prism. I have a Xamarin form with a ListView which allows editing of the list items by calling another Edit view (Upsert). There is a button on the Upsert view that validates the user's input and if valid, saves the entry to a SQLite database and returns the user to the original form (with the ListView). If it is not valid, the desired behaviour is to return to the form for correction or to allow the user to cancel and to revert to the last valid entity.

The default behaviour of the hardware back button is to leave the form without validating and to remove the parameters!

I was unable to find a behaviour to control the hardware back button, so I wrote the following View Model. This view model works fine and implements the exact behaviour that I want, but I can't help thinking that it's too complicated.

There are two classes in this sample: Mailing List (parent entity) and Mailing List Item (child entity). This is the View Model for creating/editing the Mailing List Item.

Am I missing something simple? Any comments would be appreciated...

using Prism.Commands;
using System;
using System.Diagnostics;
using Prism.Common;
using Prism.Navigation;
using Rsvp.Entities.Shared;
using Rsvp.Xamarin.App.Services;
using Xamarin.Forms;
using Rsvp.Xamarin.App.Helpers;
using Rsvp.Entity.Abstractions.EF.UnitOfWork;
using Prism.AppModel;
using Prism.Services;

namespace Rsvp.Xamarin.App.ViewModels
{
    public class MailingListItemUpsertViewModel :  ViewModelBase, INavigationAware, IPageLifecycleAware
    {
        public DelegateCommand<object> SaveCommand { get; private set; }
        private INavigationService navigationService;
        private MailingListItemService syncService;
        private IPageDialogService dialogService;

        //private Page page = PageUtilities.GetCurrentPage(Application.Current.MainPage);


        public MailingListItemUpsertViewModel(
            MailingListItemService syncService, 
            INavigationService navigationService, 
            IPageDialogService dialogService) : base(navigationService)
        {
            this.syncService = syncService;
            this.dialogService = dialogService;
            this.navigationService = navigationService;
            SaveCommand = new DelegateCommand<object>(SaveMailingListItem);
        }

        private string _title;
        public string Title
        {
            get { return _title;}
            set { SetProperty(ref _title, value); }
        }

        private MailingList _mailingList;
        public MailingList MailingList
        {
            get { return _mailingList; }
            set { SetProperty(ref _mailingList, value); }
        }

        private MailingListItem _mailingListItem;
        public MailingListItem MailingListItem
        {
            get { return _mailingListItem; }
            set { SetProperty(ref _mailingListItem, value); }
        }

        // these represent the validatable data items in the entity.  This validation rules
        // themselves are annotations on the MailingListItem object.
        private string originalEmail;
        private string originalFirstName;
        private string originalLastName;
        private string originalSalutation;


        public void OnNavigatedFrom(INavigationParameters parameters)
        {
        }

        public void OnNavigatedTo(INavigationParameters parameters)
        {
            MailingListItem = parameters.GetValue<MailingListItem>("mailingListItem");

            // these represent the validatable data items in the entity.
            originalEmail = parameters.GetValue<string>("originalEmail") ?? MailingListItem.Email;
            originalSalutation = parameters.GetValue<string>("originalSalutation") ?? MailingListItem.Salutation;
            originalFirstName = parameters.GetValue<string>("originalFirstName") ?? MailingListItem.FirstName;
            originalLastName = parameters.GetValue<string>("originalLastName") ?? MailingListItem.LastName;

            // This is the parent entity
            MailingList = parameters.GetValue<MailingList>("mailingList");

            Title = MailingList.Name;
        }

        async void SaveMailingListItem(object p)
        {
            Page page = PageUtilities.GetCurrentPage(Application.Current.MainPage);
            if (!ValidationHelper.IsFormValid(MailingListItem, page))
            {
                return;
            }

            ContinueOrDiscard(true);

        }

        public async void OnAppearing()
        {
            Page page = PageUtilities.GetCurrentPage(Application.Current.MainPage);


            // Validates the page data on appearing by applying the annotations on the MailingListItem object.
            // The only way they should be invalid is if the hardware back button has been pressed causing the 
            // form to be re-called.
            // 
            bool isValid = ValidationHelper.IsFormValid(MailingListItem, page);
        }

        public void OnDisappearing()
        {
            ContinueOrDiscard();
        }


        public async void ContinueOrDiscard(bool alreadyValidated = false)
        {

            var parameters = new NavigationParameters
            {
                { "mailingList", MailingList },
                { "mailingListItem", MailingListItem },
                { "originalEmail", originalEmail },
                { "originalSalutation", originalSalutation},
                { "originalFirstName", originalFirstName },
                { "originalLastName", originalLastName }
            };

            Page page = PageUtilities.GetCurrentPage(Application.Current.MainPage);
            if (alreadyValidated || ValidationHelper.IsFormValid(MailingListItem, page))
            {
                if (MailingListItem.Id == Guid.Empty)
                {
                    await syncService.AddAsync(MailingListItem);
                }
                else
                {
                    await syncService.UpdateAsync(MailingListItem.Id, MailingListItem);
                }
                await navigationService.NavigateAsync(
                    "/MainPage/NavigationPage/MainDetailPage/MailingListIndexPage/MailingListItemIndexPage",
                    parameters, false);
            }
            else
            {
                if (await dialogService.DisplayAlertAsync("This mailing list item is invalid.", "Would you like to continue editing the record?",
                    "Yes",
                    "No"))
                {
                    await navigationService.NavigateAsync(
                        "/MainPage/NavigationPage/MainDetailPage/MailingListIndexPage/MailingListItemIndexPage/MailingListItemUpsertPage",
                        parameters, false);
                }
                else
                {
                    MailingListItem.Email = originalEmail;
                    MailingListItem.Salutation = originalSalutation;
                    MailingListItem.FirstName = originalFirstName;
                    MailingListItem.LastName = originalLastName;
                    await navigationService.NavigateAsync(
                        "/MainPage/NavigationPage/MainDetailPage/MailingListIndexPage/MailingListItemIndexPage", parameters, false);

                }

            }

        }

    }
}

Here is the Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="http://prismlibrary.com"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="Rsvp.Xamarin.App.Views.MailingListItemUpsertPage"
             Title="{Binding Title}">
    <StackLayout  Padding="20,20,20,20">
        <StackLayout IsVisible="True" BindingContext="{Binding MailingListItem}">
        <Entry Text="{Binding Salutation}" IsVisible="True" IsEnabled="True" Placeholder="Salutation"/>
            <Label x:Name="MailingListItem_SalutationError" IsVisible="False" TextColor="Red" />
        <Entry Text="{Binding FirstName}" IsVisible="True" IsEnabled="True" Placeholder="First name"/>
            <Label x:Name="MailingListItem_FirstNameError" IsVisible="False" TextColor="Red" />
        <Entry Text="{Binding LastName}" IsVisible="True" IsEnabled="True" Placeholder="Last name"/>
            <Label x:Name="MailingListItem_LastNameError" IsVisible="False" TextColor="Red" />
        <Entry Text="{Binding Email}" IsVisible="True" IsEnabled="True" Placeholder="Email address"/>
            <Label x:Name="MailingListItem_EmailError" IsVisible="False" TextColor="Red" />
            <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding DoNotMail}" IsEnabled="True" HorizontalOptions="Start" />
                <Label Text="Do not email" HorizontalOptions="FillAndExpand" VerticalTextAlignment="Center"/>
            </StackLayout>
        </StackLayout>
        <Button Text="Ok" Command="{Binding SaveCommand}" CommandParameter="{Binding MailingListItem}"/>
</StackLayout>

</ContentPage>

MVVM model: how to change button background color?

$
0
0

How do I change the background color of a button using the MVVM?

QuizPageModel

AnsweredTrue = new Command(async () =>
{
Debug.WriteLine("True button pressed");

            // check if answer is correct
            if (_currentAnswerValue == true)

                score++;

}

AnsweredFalse = new Command(async () =>
{
Debug.WriteLine("False button pressed");

        // check if answer is correct
        if (_currentAnswerValue == false) 

score++;

      }

Xaml

                <Button x:Name="FalseButton"
                Text="Falso" 
                FontSize="25"
                CornerRadius="20"
                HeightRequest="50"
                BackgroundColor="LightPink"
                Command="{Binding AnsweredFalse}"
                Grid.Row="3" />

CheckBox control won't render inside of a TabViewControl in a Rg.Plugins.Popup

$
0
0

Tis the strangest thing. I'm using Rg.Plugins.Popups with the Xam.Plugin.TabView (and the latest Xamarin.Forms, although I've tried a few of the 4.6 versions too).

On Android, the Xamarin.Forms CheckBox won't render inside of a TabViewControl in a popup. It'll render just fine if not in the TabView, but no matter where/how I place it (wrap in a grid, stacklayout, frame etc), it won't render inside of a TabView. Works fine in UWP though.

The weird thing is, if I create a stand-alone Xamarin.Forms Android project to replicate this, it renders just fine.

There are no exceptions at all, it just isn't there.

I'm at a loss as to figure out why it isn't rendering!

Viewing all 79144 articles
Browse latest View live


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