【发布时间】:2019-11-18 09:48:00
【问题描述】:
我想在窗口关闭或应用程序崩溃时将数据保存到应用程序。
当用户写入条目时,数据会存储在属性中,但由于某种原因绑定不起作用。
为此,我参加了有关 Udemy 的课程。我认为这与引用 PCL 中的不同位置有关。
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TheIVInventory.ViewModels
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AddItemPage : ContentPage
{
public AddItemPage()
{
InitializeComponent();
BindingContext = Application.Current;
}
private void Button_Clicked(object sender, EventArgs e) //Item added click.
{
}
}
}
Xaml:
<ContentPage
BackgroundColor="#104850"
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="TheIVInventory.ViewModels.AddItemPage">
<StackLayout VerticalOptions="Center" x:Name="formLayout" Margin="20">
<Entry PlaceholderColor="White" Keyboard="Chat" Margin="40" Placeholder="Item Name" TextColor="White" Text="{Binding ItemName}"></Entry>
<Entry PlaceholderColor="White" Keyboard="Numeric" Margin="40" Placeholder="Item Price MIN (€)" TextColor="White"></Entry>
<Entry PlaceholderColor="White" Keyboard="Numeric" Margin="40" Placeholder="Item Price MAX (€)" TextColor="White"></Entry>
<Editor PlaceholderColor="White" Margin="40" VerticalOptions="FillAndExpand" Keyboard="Chat" Placeholder="Item Description" TextColor="White"></Editor>
<Button Text="Save" BackgroundColor="#80EEFF" Margin="10" Clicked="Button_Clicked" ></Button>
<Image Source="konjakki.png" Scale="0.15" AnchorY="0" BackgroundColor="#104850" ></Image>
</StackLayout>
</ContentPage>
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TheIVInventory
{
public partial class App : Application
{
// Setting the item add members.
private const string itemNameKey = "Name";
private const string itemMinPrice = "0";
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage())
{
BarBackgroundColor = Color.FromHex("#104850"),
BarTextColor = Color.White
}; // Making the navigation possible.
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
// Making the add item properties.
public string ItemName
{
get
{
if (Properties.ContainsKey(itemNameKey))
return Properties[itemNameKey].ToString();
return "";
}
set
{
Properties[ItemName] = value;
}
}
public string ItemMinPrice
{
get
{
if (Properties.ContainsKey(itemMinPrice))
return Properties[itemMinPrice].ToString();
return "";
}
set
{
Properties[itemMinPrice] = value;
}
}
}
}
【问题讨论】:
-
你为什么将
Application.Current设置为你的BindingContext?
标签: c# visual-studio xaml xamarin