在我的应用程序中,我有多个步进器以及相应的条目,以显示每个步进器的当前值。我正在尝试使用Xamarin.Essentials:Preferences保存该值,以便在重新打开该应用程序时供以后使用,但是“ Preferences”似乎没有保存步进值和/或在重新打开该应用程序时输入该值。>
这是xaml的一个例子...
<Grid x:Name="PurchasePriceGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width=".6*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<Label Text="Purchase Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2" TranslationX="15"
Grid.Column="0" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
<customentry:MyEntry x:Name="PurchasePriceEntry" Text="{Binding Source={x:Reference PurchasePriceStepper}, Path=Value, FallbackValue=0}"
TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="10"
Grid.Column="1" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="End" MaxLength="5"
TextChanged="PurchasePriceEntry_Completed" />
<Stepper x:Name="PurchasePriceStepper" Grid.Column="2" HorizontalOptions="Center" VerticalOptions="Center" Scale=".7" TranslationX="3"
Maximum="5" Minimum=".01" Increment=".01" Value="{Binding PurchasePriceStepperValue}" />
</Grid>
这是C#...
using Xamarin.Essentials;
...
public double PurchasePriceStepperValue
{
get => Preferences.Get(nameof(PurchasePriceStepperValue), 1.75);
set
{
Preferences.Set(nameof(PurchasePriceStepperValue), value);
OnPropertyChanged(nameof(PurchasePriceStepperValue));
}
}
这是Android MainActivity.cs ...
using Xamarin.Essentials;
...
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
Xamarin.Essentials.Platform.Init(this, bundle);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
我是编程新手,并且花了多个小时尝试多种不同的方法,以弄清为什么Xamarin.Essentials:Preferences不会保存步进值并将其输入到条目中。我已经在所有项目中实现了NuGet包。如果有帮助,我可以尝试提供更多代码。
答案 0 :(得分:1)
重新打开应用程序时的默认值为0.01 ,表示绑定无效。
我在Xaml
和MainActivity.cs
中使用与您相同的代码,并使用下面的代码,如下所示:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
PurchasePriceModel model = new PurchasePriceModel();
BindingContext = model;
}
}
class PurchasePriceModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public double PurchasePriceStepperValue
{
get => Preferences.Get(nameof(PurchasePriceStepperValue), 1.75);
set
{
Preferences.Set(nameof(PurchasePriceStepperValue), value);
PropertyChanged(this, new PropertyChangedEventArgs(nameof(PurchasePriceStepperValue)));
}
}
public PurchasePriceModel()
{
}
}
它对我有用。请检查您的BindingContext
和Model
中的代码。