![](/img/trans.png)
[英]Xamarin.Forms Binding only updating ViewModel property with default values
[英]ViewModel not updating form (Xamarin.Forms)
我正在嘗試使用 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;
}
}
}
從ItemCount.set
您正在提升PropertyChanged
,這是視圖根據視圖模型的狀態更新所必需的。 否則視圖將不得不輪詢狀態變化,這將浪費資源,尤其是在我們希望避免因過度使用處理器而耗盡電池的移動設備上。
無論如何,當你在做的時候直接設置itemCount
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
itemCount++;
return true;
}
ItemCount.set
永遠不會被調用,因此PropertyChanged
永遠不會被引發,並且視圖沒有機會確定視圖模型改變了它的狀態。 此外,我猜ItemCount
必須在 UI 主線程中設置,因此您必須通過Device.BeginInvokeOnMainThread
包裝對ItemCount.set
的Device.BeginInvokeOnMainThread
( 請參閱文檔)
將代碼更改為
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
Device.BeginInvokeOnMainThread (() =>
{
ItemCount++;
});
return true;
}
並且視圖應該更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.