"Не знаю о Xamarin.Forms.Color" - PullRequest
       0

"Не знаю о Xamarin.Forms.Color"

0 голосов
/ 06 февраля 2020

Почему выдается код «Не знаю о Xamarin.Forms.Color»?

Сведения об исключении:

System.AggregateException Zpráva=One or more errors occurred. (Don't know about Xamarin.Forms.Color) Zdroj= StackTrace: at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2027 at System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) [0x00043] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2759 at System.Threading.Tasks.Task.Wait () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2625 at Notes.Data.NoteDatabase..ctor (System.String dbPath) [0x00015] in C:\Users\foksak\source\repos\Notes\Notes\Notes\Data\NoteDatabase.cs:15 at Notes.App.get_Database () [0x0000e] in C:\Users\foksak\source\repos\Notes\Notes\Notes\App.xaml.cs:18 at Notes.NotesPage.OnAppearing () [0x0001b] in C:\Users\foksak\source\repos\Notes\Notes\Notes\NotesPage.xaml.cs:19 at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.39(intptr,intptr at (wrapper native-to-managed) Android.Runtime.DynamicMethodNameCounter.39(intptr,intptr)

Примечание модели:

namespace Notes.Models
{
    public class Note
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Text { get; set; }
        public string Title { get; set; }
        public string Picture { get; set; }
        public string Colorr { get; set; }
        public Color Colorrr { get; set; }
    }
}

c# страницы ввода данных:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NoteEntryPage : ContentPage
{
    Dictionary<string, string> dic = new Dictionary<string, string>() {
        {"Color1","#d8daea"},
        {"Color2", "#ecd67b"},
        {"Color3", "#3f6018"},
        {"Color4", "#ff8847" }
    };

    public NoteEntryPage()
    {
        InitializeComponent();
    }
    async void OnSaveButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        string x = dic[note.Colorr];
        note.Colorrr = Color.FromHex(x);
        await App.Database.SaveNoteAsync(note);
        await Navigation.PopAsync();
    }

    async void OnDeleteButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        await App.Database.DeleteNoteAsync(note);
        await Navigation.PopAsync();
    }
}

Ввод работает. Проблема была также в том случае, когда я вручную написал "#ff8847" вместо x.

Данные на экране отображаются с кодом ниже. Заполнение данных в c#:

protected override async void OnAppearing()
{
    base.OnAppearing();

    listView.ItemsSource = await App.Database.GetNotesAsync();
}

Xaml:

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="Notes.NotesPage">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="+"
                     Clicked="OnNoteAddedClicked" />
    </ContentPage.ToolbarItems>
    <ListView x:Name="listView"
              Margin="20" RowHeight="80"
              ItemSelected="OnListViewItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate >
                <ViewCell>
                    <Grid VerticalOptions="FillAndExpand" HorizontalOptions="Fill">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="auto"/>
                            <ColumnDefinition Width="auto"/>
                            <ColumnDefinition Width="auto"/>
                        </Grid.ColumnDefinitions>

                        <Grid.RowDefinitions >
                            <RowDefinition Height="auto"/>
                            <RowDefinition Height="auto"/>
                        </Grid.RowDefinitions>

                        <StackLayout Orientation="Horizontal" Grid.Column="1" Grid.Row="0">
                            <Label Text="{Binding Title}" FontSize="22" FontAttributes="Bold" />
                        </StackLayout>

                        <Label Text="{Binding Text}" Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2"/>

                        <Frame CornerRadius="5" HasShadow="true" Grid.RowSpan="2" BackgroundColor="{Binding Colorrr}" Margin="7" WidthRequest="35">
                            <Image Source="{Binding Picture}" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="30"/>
                        </Frame>

                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

1 Ответ

1 голос
/ 06 февраля 2020

Вы не можете иметь поле Color в своей базе данных sqlite, поэтому игнорируйте его.

namespace Notes.Models
{
    public class Note
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Text { get; set; }
        public string Title { get; set; }
        public string Picture { get; set; }
        public string Colorr { get; set; }

        [Ignore]
        public Color  Colorrr { get; set; }
    }
}

Вы также должны инициализировать свое поле Colorrr, прежде чем привязать его к своему представлению следующим образом:

note.Colorrr = note.Colorr.FromHex(x);

Затем назовите свой фрейм, чтобы обновить цвет, и удалите привязку:

<Frame x:Name="ColorFrame" CornerRadius="5" HasShadow="true" Grid.RowSpan="2" Margin="7" WidthRequest="35">
    <Image Source="{Binding Picture}" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="30"/>
</Frame>

И обновите его в своем методе сохранения:

async void OnSaveButtonClicked(object sender, EventArgs e)
{
    var note = (Note)BindingContext;
    string x = dic[note.Colorr];
    ColorFrame.BackgroundColor = Color.FromHex(x);
    await App.Database.SaveNoteAsync(note);
    await Navigation.PopAsync();
}

Затем он должен работать как положено.

Другой более чистый путь: используйте шаблон MVVM и создайте NoteViewModel, реализующий INotifyPropertyChanged, который обернет ваш Note объект.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...