Формы Xamarin: ссылка на элемент XAML из модели cs - PullRequest
0 голосов
/ 22 апреля 2020

Прежде всего, я не разработчик Xamarin, поэтому, может быть, некоторые c ошибки передаются мне в голову.

Мне нужно изменить работающее приложение Xamarin Forms в Visual Studio 2017. Необходимо скрыть клавиатуру после того, как какой-либо текст введен в «DisplayPromptAsyn c» и показать индикатор активности, пока он выполняет какой-то процесс. Я подумал, что для этого нужно сначала установить фокус на другой элемент на экране, а затем установить для свойства «IsBusy» (которое определено в «BasePageModel») значение true. Уже был элемент Frame, который, кажется, делает это, хотя он никогда не упоминался в обратном коде. Но ничего не работает.

Я добавил «x: Name =« Processing »» в ActivityIndicator в XAML, но не могу вызвать его из cs. Он продолжает говорить: The name "Processing" does not exist in the current context. Действительно пытался установить то же самое x: Name в других элементах, таких как кнопки, и т. Д. c .. в случае, если на ActivityIndicator нельзя ссылаться, но я не могу его вызвать. Видел, что у некоторых людей были проблемы с этим и пытался применить это: Xamarin. Имя authorEntry не существует в текущем контексте , но оно не будет работать, ни перезапускать Visual Studio, ни перестраивать приложение. Поэтому я подумал, может, есть кое-что, о чем я не знаю, и я просто не делаю / делаю это неправильно.

Во-вторых, не имеет значения, если я установлю значение IsBusy в true внутри Device.BeginInvokeOnMainThread. Он не появится на экране, чтобы показать ActivityIndicator между тем, как он обрабатывается.

Я поставил отметку "/ * ADDED * /" в коде, который я добавил в cs (на самом деле это не так много, просто пара строк в cs и свойство "x: Name" в XAML)

Это экран (файл XAML в "Pages"):

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="AFJP.Pages.ReportPage" BackgroundColor="{StaticResource BackgroundDefault}">
    <NavigationPage.TitleView>
        <Grid HorizontalOptions="FillAndExpand">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Label Text="{Binding CurrentBox.ClaseId}" Grid.Column="0" VerticalOptions="Center" TextColor="White">
                <Label.FontSize>
                    <OnPlatform x:TypeArguments="x:Double">
                        <On Platform="iOS" Value="12" />
                        <On Platform="Android" Value="12" />
                    </OnPlatform>
                </Label.FontSize>
            </Label>
            <Image Source="Images/Image.png" Grid.Column="1" WidthRequest="80" VerticalOptions="Center" Margin="0,0,0,0" />
            <Label Text="{Binding CurrentBox.PalletId}" Grid.Column="2" HorizontalOptions="End" VerticalOptions="Center" TextColor="White" Margin="0,0,5,0">
                <Label.FontSize>
                    <OnPlatform x:TypeArguments="x:Double">
                        <On Platform="iOS" Value="12" />
                        <On Platform="Android" Value="12" />
                    </OnPlatform>
                </Label.FontSize>
            </Label>
        </Grid>
    </NavigationPage.TitleView>
    <ContentPage.Content>
        <Grid>
            <StackLayout Orientation="Vertical" HorizontalOptions="Fill" VerticalOptions="CenterAndExpand" Margin="40">
                <Button Text="Check Box" BackgroundColor="{StaticResource ButtonGray}" TextColor="{StaticResource ButtonFont}" Command="{Binding CheckBoxCmd}" />
                <Button Text="Send Box" BackgroundColor="{StaticResource ButtonBlue}" TextColor="White" Margin="0,30, 0,10" Command="{Binding SendBoxCmd}" />
                <Button Text="Cancel Box" BackgroundColor="{StaticResource ButtonBlue}" TextColor="White" Margin="0,10" Command="{Binding CancelBoxCmd}" />
            </StackLayout>
            <Frame BackgroundColor="White" Opacity="0.8" Padding="10" IsVisible="{Binding IsBusy}" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All" >
                <StackLayout VerticalOptions="Center" HorizontalOptions="CenterAndExpand">
                    <ActivityIndicator HeightRequest="50" HorizontalOptions="Center" VerticalOptions="Center" Color="{StaticResource ButtonBlue}" IsRunning="{Binding IsBusy}" x:Name="Processing"/>
                    <Label Text="Closing" HorizontalOptions="Center" HorizontalTextAlignment="Center" FontAttributes="Bold" TextColor="{StaticResource ButtonBlue}" Margin="0,5" />
                </StackLayout>
            </Frame>
        </Grid>
    </ContentPage.Content>
</ContentPage>

И это CS (файл CS в PageModels):

    using System;
    using System.Net;
    using System.Threading.Tasks;
    using AFJP.Models;
    using AFJP.PageModels.Base;
    using AFJPServices.Interfaces;
    using AFJPServices.Services;
    using Newtonsoft.Json;
    using RestSharp;
    using Xamarin.Forms;

    namespace AFJP.PageModels
    {
        public class ReportPageModel : BasePageModel
        {
            readonly IBoxService _boxServices;
            private readonly string authToken;

            Box currentBox;
            public Box CurrentBox
            {
                get { return currentBox; }
                set
                {
                    if (!Equals(currentBox, value))
                    {
                        currentBox = value;
                        RaisePropertyChanged(nameof(currentBox ));
                    }
                }
            }

            public Command CheckBoxCmd=> new Command(async () => await PushAsync<ReviewItemsPageModel>());

            public Command SendBoxCmd => new Command(async () => { SendBox(); });

            public Command CancelBoxCmd => new Command(async () => { CancelBox(); });


            async Task CancelBox()
            {
                if (await Application.Current.MainPage.DisplayAlert("Cancel", "Are you sure you want to cancel this Box?", "Yes", "No"))
                {
                    string BoxId = Application.Current.Properties["BoxId"].ToString();
                    IRestResponse boxresponse = await _boxServices.PostCancelBox(authToken, receipId);

                    switch (boxresponse.StatusCode)
                    {
                        case HttpStatusCode.OK:
                            Application.Current.Properties.Remove("currentBox");
                            await Application.Current.SavePropertiesAsync();
                            await Application.Current.MainPage.Navigation.PopAsync();
                            break;
                        case HttpStatusCode.BadRequest:
                            Device.BeginInvokeOnMainThread(async () =>
                            {
                                await Application.Current.MainPage.DisplayAlert("Error", "This box already has been already sent and cannot be cancelled.", "OK");
                            });
                            break;
                        case HttpStatusCode.NotFound:
                            Device.BeginInvokeOnMainThread(async () =>
                            {
                                await Application.Current.MainPage.DisplayAlert("Error", "Box not found", "OK");
                            });
                            break;
                        default:
                            Device.BeginInvokeOnMainThread(async () =>
                            {
                                await Application.Current.MainPage.DisplayAlert("Something went wrong", "Please contact IT", "OK");
                            });
                            break;
                    }
                }

            }

            async Task SendBox()
            {
                if (Application.Current.Properties.ContainsKey("PendingItems") && !Convert.ToBoolean(Application.Current.Properties["PendingItems"]))
                {
                    if (await Application.Current.MainPage.DisplayAlert("Close", "Are you sure you want to close the box?", "Yes", "No"))
                    {

                        Application.Current.Properties.Remove("currentBox");
                        await Application.Current.SavePropertiesAsync();

                        if (Application.Current.Properties.ContainsKey("userData"))
                        {
                            User userData = JsonConvert.DeserializeObject<User>((Application.Current.Properties["userData"].ToString()));

                            if (userData != null && userData.Role == "PM")
                            {
                                string ContainerID = "";
                                while (ContainerID == "")
                                {
                                    ContainerID = await Application.Current.MainPage.DisplayPromptAsync("", "Enter Case of the box", "OK", null, null, 30, Keyboard.Plain);

                                    if (String.IsNullOrEmpty(ContainerID))
                                        await Application.Current.MainPage.DisplayAlert("Warning ", "You must enter the ID", "OK");
                                }

                                Device.BeginInvokeOnMainThread(() => { /* ADDED */
                                    IsBusy = true;
                                    FormLoading.Focus();
                                });

                                Device.BeginInvokeOnMainThread(async () =>
                                {
                                    string receipId = Application.Current.Properties["receiptId"].ToString();
                                    await _boxServices.PostCloseBox(authToken, BoxId, Case);
                                });

                                Device.BeginInvokeOnMainThread(() => { IsBusy = false; }); /* ADDED */
                                await Application.Current.MainPage.Navigation.PopAsync();    

                            }
                            else
                            {
                                Device.BeginInvokeOnMainThread(async () =>
                                {
                                    string BoxId = Application.Current.Properties["BoxId"].ToString();
                                    await _receiptServices.PostCloseBox(authToken, BoxId, null);
                                });

                                await Application.Current.MainPage.Navigation.PopAsync();
                            }
                        }
                    }
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Close", "You have to send the Box to Close it.", "OK");
                }
            }

        }
    }
...