【发布时间】:2020-03-10 14:20:33
【问题描述】:
我正在尝试让 ViewModel 更新 XAML 页面上的计数器,但无法弄清楚我做错了什么...
itemCount 的初始值显示良好,但每次递增后未更新。
这里是 XAML 源代码:
<?xml version="1.0" encoding="utf-8" ?>
<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"
xmlns:maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
xmlns:local="clr-namespace:XamarinFormsTest01"
mc:Ignorable="d"
x:Class="XamarinFormsTest01.MainPage">
<StackLayout>
<Label x:Name="lblMain" Text="{Binding ItemCount}"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" >
<Label.BindingContext>
<local:ItemCountViewModel />
</Label.BindingContext>
</Label>
<Button x:Name="BtnStart" Text="start" Pressed="BtnStart_Pressed" />
<Button x:Name="BtnStop" Text="stop" Pressed="BtnStop_Pressed" />
</StackLayout>
</ContentPage>
以及 ViewModel 源代码:
public class ItemCountViewModel : INotifyPropertyChanged
{
private static ItemCountViewModel instance = new ItemCountViewModel();
public static ItemCountViewModel GetInstance()
{
return instance;
}
int itemCount;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public ItemCountViewModel()
{
itemCount = 0;
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
itemCount++;
return true;
}
);
}
public int ItemCount
{
set
{
itemCount = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ItemCount"));
}
get
{
return itemCount;
}
}
}
【问题讨论】:
-
不妨看看下面的答案stackoverflow.com/a/56487270/8293694。可能会帮到你。
-
谢谢,我会检查那个帖子,但问题已经解决了:)
标签: c# android forms xamarin viewmodel