如何解决无法通过Xamarin中的代码访问列表的x:Name
我不知道为什么我无法通过任何帮助plz背后的代码访问xaml文件中列表的x:Name?
我是Xamarin和Im的新手,我试图构建一个基本项目,我尝试通过Google搜索一些解决方案,但是我发现我的代码是正确的,所以现在不做什么。
此处是XML文件Posts.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"
x:Class="FavPosts.Posts">
<ListView x:Name="listview" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal"
Padding="5">
<Label HorizontalOptions="StartAndExpand"/>
<Button Text="Favorite"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
后面的代码是Posts.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace FavPosts
{
[XamlCompilation(XamlCompilationoptions.Compile)]
public partial class Posts : ContentPage
{
public Posts()
{
InitializeComponent();
}
public class Post
{
public string Status { get; set; }
public string Details { get; set; }
}
List<Post> Posty = new List<Post> {
new Post { Status="f1",Details="D1" },new Post { Status="f2",Details="D2"}
};
listview.ItemsSource = Posty;
}
}
,这是错误
解决方法
语句“ listview.ItemsSource = Posty1;”位置错误。它应该在方法中。
public Posts() {
InitializeComponent();
listview.ItemsSource=Posty1;
}
,
您应该将Post类放在Posts之外! 要“自动”创建列表,应将其放置在构造函数中。但是您的主要问题是Post类必须在外面
namespace FavPosts
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Posts : ContentPage
{
public Posts()
{
InitializeComponent();
List<Post> Posty = new List<Post> {
new Post { Status="f1",Details="D1" },new Post { Status="f2",Details="D2"}
};
listview.ItemsSource = Posty;
}
}
public class Post
{
public string Status { get; set; }
public string Details { get; set; }
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。