【发布时间】:2020-11-05 10:43:56
【问题描述】:
由于某些特殊原因我不能使用Xamarin.Forms Data Binding,我必须直接更新ListView中ItemTemplate创建的视图属性。
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="TestListView.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<Grid>
<ListView x:Name="TestListView" />
<Button
Clicked="Button_Clicked"
HorizontalOptions="Center"
Text="Change last appearing text"
VerticalOptions="Center" />
</Grid>
</ContentPage>
MainPage.xaml.cs
using System.Linq;
using Xamarin.Forms;
namespace TestListView {
public partial class MainPage : ContentPage {
private int lastApprearingItemIndex = -1;
public MainPage() {
InitializeComponent();
TestListView.ItemTemplate = new DataTemplate(() => {
return (new ViewCell() {
View = new Label()
});
});
TestListView.ItemsSource = Enumerable.Range(1, 10000).ToArray();
TestListView.ItemAppearing += TestListView_ItemAppearing;
}
private void TestListView_ItemAppearing(object sender, ItemVisibilityEventArgs e) {
lastApprearingItemIndex = e.ItemIndex;
((Label)(((ViewCell)(TestListView.TemplatedItems[e.ItemIndex])).View)).Text = "test text for id " + (int)(e.Item);
}
private void Button_Clicked(object sender, System.EventArgs e) {
((Label)(((ViewCell)(TestListView.TemplatedItems[lastApprearingItemIndex])).View)).Text = "(changed)test text for id " + lastApprearingItemIndex;
}
}
}
但在 UWP 中它什么也没显示
它在 WPF 中也运行良好。
所以我有两个问题:
1,为什么它在 UWP 中不起作用?
2、ListView会在android中复用ListAdapter等item的view吗?
【问题讨论】:
-
据我所知,您必须使用 ObservableCollection,这样它才能通知 UI。我认为这里的问题不是它不更新,而是它只是不更新 UI。进行更改后查看 ItemsSource 的值。
-
不能直接修改UI,需要使用绑定来完成
标签: c# xaml xamarin xamarin.forms xamarin.forms.listview