持续更新ListView模板中的标签



我有一个对象列表,我将绑定到ListView,并使用DataTemplate在Xamarin应用程序中显示。到目前为止,很简单。但关键是,我希望其中一个控件(特别是标签)不断更新。

到目前为止,这就是我所拥有的。。。

<ListView x:Name="ItemsListView"
ItemsSource="{Binding Items}"
VerticalOptions="FillAndExpand"
HasUnevenRows="true"
RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="true"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
CachingStrategy="RecycleElement"
ItemSelected="OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10">
<Label Text="{Binding Title}"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemTextStyle}"
FontSize="16" />
<mycountdown:TimerLabel Text="{Binding TimeRemainingString}"
Style="{DynamicResource ListItemDetailTextStyle}"
FontSize="13" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

还有我的TimerLabel类的代码。。。

public class TimerLabel : Label
{
private bool beating;
public TimerLabel()
{
StartHeartbeat();
}
public void StartHeartbeat()
{
//only start beating again if not currently beating.
if (!beating)
{
beating = true;
Heartbeat();
}
}
public void StopHeartbeat()
{
beating = false;
}
async void Heartbeat()
{
while (beating)
{
this.Text = DateTime.UtcNow.ToLongTimeString();
}
}
}

有效,但问题是,即使我离开页面,列表中每个项目的心跳也会继续运行。

理想情况下,心跳只对屏幕上可见的项目运行,但我会让它们全部运行,并在离开页面时禁用它们。

问题是我不知道如何从页面的代码隐藏或视图模型访问StopHeartbeat()方法。

它也不会仅限于标签。我最终会有一些其他控件需要在UI线程中不断更新,但这是最简单的一个。

如果有其他方法我应该这样做,请这样说。

谢谢!

如果您在ListItem Source中绑定List,请将其从List更改为ObservableCollection如果有任何问题,请告诉我,或者您也可以上传viewModel代码

被我帖子中的顶部评论回答。