gpt4 book ai didi

c# - 如何设置ListView的ItemsSource?

转载 作者:太空狗 更新时间:2023-10-29 20:30:29 31 4
gpt4 key购买 nike

这里我定义了我的数据myListOfEmployeeObjects:

public class App : Application
{
public List<Employee> myListOfEmployeeObjects;

public App ()
{
Employee emp1 = new Employee () {
FirstName = "Max",
LastName = "Mustermann",
Twitter = "@fake1"
};
Employee emp2 = new Employee () {
FirstName = "Evy",
LastName = "Mustermann",
Twitter = "@fake2"
};
myListOfEmployeeObjects = new List<Employee> {
emp1, emp2
};
MainPage = new NavigationPage (new EmployeeListPage ());
}
}

比起我的 XAML,我在其中设置了 ItemsSource:

<ListView x:Name="listView"
IsVisible="false"
ItemsSource="{x:Static local:App.myListOfEmployeeObjects}"
ItemSelected="EmployeeListOnItemSelected">

这应该有效吗?因为我得到

Xamarin.Forms.Xaml.XamlParseException: Type App not found in xmlns

public partial class EmployeeListPage : ContentPage {

private ListView listView;

private void InitializeComponent() {
this.LoadFromXaml(typeof(EmployeeListPage)); // here the exception is thrown
listView = this.FindByName <ListView>("listView");
}
}

如何设置 XAML 的 ItemsSource

编辑:

现在我尝试了 user2425632 的建议如果我进行以下更改,它就会起作用:

  1. xmlns:local="clr-namespace:HelloXamarinFormsWorld;assembly=HelloXamarinFormsWorld" 添加到我的 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:local="clr-namespace:HelloXamarinFormsWorld;assembly=HelloXamarinFormsWorld"
x:Class="HelloXamarinFormsWorld.EmployeeListPage"
Title="Employee List">
<ContentPage.Content>

当然,您必须更改名称以适合您的项目。

  1. 显示 ListView

我删除了 IsVisibleItemSelected

<ListView ItemsSource="{x:Static local:App.myListOfEmployeeObjects}">
  1. 让一切都静态化

它必须是静态的,否则你会得到

No static member found for local:App.myListOfEmployeeObjects

public static List<Employee> myListOfEmployeeObjects { private set; get; }

public static void GetAllEmployees(){
Employee emp1 = new Employee () {
FirstName = "Max",
LastName = "Mustermann",
Twitter = "@fake1"
};
Employee emp2 = new Employee () {
FirstName = "Eva",
LastName = "Mustermann",
Twitter = "@fake2"
};
myListOfEmployeeObjects = new List<Employee> {
emp1, emp2
};
}

public App ()
{
GetAllEmployees ();
MainPage = new NavigationPage (new EmployeeListPage ());
}

最佳答案

所以我实际上并没有抽出时间自己做这件事,但是通过阅读文档我有一个建议可能值得你尝试。

ItemsSource="{x:Static local:App.myListOfEmployeeObjects}"

在您的 xaml 中,您说过源是静态的,但查看您的 .cs 文件却不是。尝试以下操作:

public static List<Employee> myListOfEmployeeObjects { private set; get; }

然后尝试使用静态函数设置对象,例如:

static App() {
myListOfEmployeeObjects = something;
}

然后该列表应该在页面上可见。

我使用了以下您可能会觉得有用的链接:

Xamarin documentation on data-binding

Example cs code

Example xaml code

希望对您有所帮助。

关于c# - 如何设置ListView的ItemsSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28738090/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com