C# 我可以直接在Xamarin.Forms中使用ListView的TemplatedItems来更新属性吗?
由于某些特殊原因,我不能使用,我必须直接更新由ListView中的ItemTemplate创建的view的属性 MainPage.xamlC# 我可以直接在Xamarin.Forms中使用ListView的TemplatedItems来更新属性吗?,c#,xaml,xamarin,xamarin.forms,xamarin.forms.listview,C#,Xaml,Xamarin,Xamarin.forms,Xamarin.forms.listview,由于某些特殊原因,我不能使用,我必须直接更新由ListView中的ItemTemplate创建的view的属性 MainPage.xaml <?xml version="1.0" encoding="utf-8" ?> <ContentPage x:Class="TestListView.MainPage" xmlns="http://xamarin.com/schemas/2014/form
<?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>
该测试在android中运行良好
但在UWP中,它什么也没有显示
它在WPF中也运行良好
所以我有两个问题:
1,为什么它在UWP中不起作用
2、ListView会像android一样重用项目视图吗
1,为什么它在UWP中不起作用
因为您对listview使用了ViewCell
,并且没有绑定任何值
如果您坚持不使用数据绑定,您可以像下面的格式一样更改背景代码
public partial class MainPage : ContentPage
{
ObservableCollection<string> employees;
public MainPage()
{
InitializeComponent();
employees = new ObservableCollection<string>();
for (int i = 0; i < 100; i++)
{
employees.Add("test text for id " + i);
}
TestListView.ItemsSource = employees;
}
protected override void OnAppearing()
{
base.OnAppearing();
}
private void Button_Clicked(object sender, System.EventArgs e)
{
//set the id that you want to change
employees[1] = "test111";
}
}
public分部类主页面:ContentPage
{
可观察收集员工;
公共主页()
{
初始化组件();
员工=新的可观察集合();
对于(int i=0;i<100;i++)
{
添加(“id的测试文本”+i);
}
TestListView.ItemsSource=员工;
}
出现时受保护的覆盖无效()
{
base.OnAppearing();
}
已单击私有无效按钮(对象发送者,System.EventArgs e)
{
//设置要更改的id
员工[1]=“test111”;
}
}
这里是运行gif。
2、ListView会在android中重用ListAdapter这样的项目视图吗
在xamarin表单中,没有ListAdapter
,因此我强烈建议您使用数据绑定,代码将更加优雅和简单。这里有一篇关于它的有用文章
据我所知,您必须使用ObservableCollection,这样它才能通知UI。我认为这里的问题不是它没有更新,而是它没有更新UI。在进行更改后,请查看ItemsSource的值。您不能直接修改UI,您需要使用绑定来完成此操作
public partial class MainPage : ContentPage
{
ObservableCollection<string> employees;
public MainPage()
{
InitializeComponent();
employees = new ObservableCollection<string>();
for (int i = 0; i < 100; i++)
{
employees.Add("test text for id " + i);
}
TestListView.ItemsSource = employees;
}
protected override void OnAppearing()
{
base.OnAppearing();
}
private void Button_Clicked(object sender, System.EventArgs e)
{
//set the id that you want to change
employees[1] = "test111";
}
}