我是 Xamarin 的新手 - 我遇到了問題。如何在 SQLite 的標簽中顯示列值的總和?
這是我的代碼。
模型預算
public class Budget
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int Money { get; set; }
}
SQLite 資料庫 方法 GetBudgets()
public class StatisticsService
{
static SQLiteAsyncConnection db;
static async Task Init()
{
if (db != null)
return;
// Get an absolute path to the database file
var databasePath = Path.Combine(FileSystem.AppDataDirectory, "MyApp.db");
db = new SQLiteAsyncConnection(databasePath);
await db.CreateTableAsync<Budget>();
}
public static async Task AddBudget(int money)
{
await Init();
var budget = new Budget
{
Money = money,
};
await db.InsertAsync(budget);
}
public static async Task<int> GetBudgets()
{
await Init();
int sumBudgets = await db.ExecuteScalarAsync<int>("SELECT SUM(Money) FROM Budget");
return sumBudgets;
}
}
視圖模型代碼
int budgetMoney;
public int BudgetMoney { get => budgetMoney; set => SetProperty(ref budgetMoney, value); }
public AsyncCommand OpenAddBudget { get; }
public AsyncCommand ListBudget { get; }
public StatisticsViewModel()
{
OpenAddBudget = new AsyncCommand(Open);
ListBudget = new AsyncCommand(ListGetBudget);
}
async Task Open()
{
var route = "addBudgetPage";
await Shell.Current.GoToAsync(route);
}
async Task ListGetBudget()
{
budgetMoney = await StatisticsService.GetBudgets();
}
查看 Xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.Views.Statistics"
xmlns:viewmodels="clr-namespace:MyApp.ViewModels"
xmlns:model="clr-namespace:MyApp.Models">
<ContentPage.BindingContext>
<viewmodels:StatisticsViewModel/>
</ContentPage.BindingContext>
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add" Command="{Binding OpenAddBudget}"/>
</ContentPage.ToolbarItems>
<ContentPage.Content>
<StackLayout>
<Button Text="Reload" Command="{Binding ListBudget}"/>
<Label Text="{Binding BudgetMoney}"/>
</StackLayout>
</ContentPage.Content>
我沒有收到任何錯誤,但是在除錯時我注意到變數 sumBudget 始終為 0。我的 SQLite 語法有什么問題嗎?
public static async Task<int> GetBudgets()
{
await Init();
int sumBudgets = await db.ExecuteScalarAsync<int>("SELECT SUM(Money) FROM Budget");
return sumBudgets;
}
不幸的是,我不知何故沒有走得更遠。目標應該是,當我單擊“重新加載”按鈕時,各個預算的總和會顯示在標簽中。
謝謝你的幫助!
編輯:呼叫 AddButton
public class AddBudgetViewModel : ViewModelBase
{
int money;
public int Money { get => money; set => SetProperty(ref money, value); }
public AsyncCommand SaveCommand { get; }
public AddBudgetViewModel()
{
SaveCommand = new AsyncCommand(Save);
}
async Task Save()
{
if (money == 0)
return;
await StatisticsService.AddBudget(money);
await Shell.Current.GoToAsync("..");
}
}
uj5u.com熱心網友回復:
這是設定私有欄位budgetMoney,不呼叫PropertyChanged
budgetMoney = await StatisticsService.GetBudgets();
相反,您應該設定public 屬性,它將呼叫PropertyChanged
BudgetMoney = await StatisticsService.GetBudgets();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473722.html
