【发布时间】:2021-10-23 08:49:59
【问题描述】:
我的 xamarin 表单列表视图有问题。我创建了一个列表视图,其中包含绑定到自定义类列表的项目源。在 app.xaml.cs 中,我有完全相同的列表。在另一种形式中,我正在更新驻留在 app.xaml.cs 中的列表。当带列表视图的第一个表单恢复时,在出现时我设置了绑定到 app.xaml.cs 中列表的本地列表。但是,列表视图 UI 中的项目不会更新。有人可以帮我解决这个问题吗?
MainPage.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="TrackExpensesApp.MainPage">
<ContentPage.ToolbarItems>
<ToolbarItem Text="+"
Clicked="OnAddExpenseClicked" />
</ContentPage.ToolbarItems>
<ListView x:Name="ExpenseEntriesListView"
ItemsSource="{Binding ExpenseEntries}"
SelectionMode="Single"
ItemSelected="ExpenseEntriesItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Padding="10"
RowDefinitions="Auto, *"
ColumnDefinitions="Auto, *">
<Label Grid.ColumnSpan="2"
Text="{Binding Name}"
VerticalOptions="End" />
<Label Grid.Row="1"
Text="{Binding DateCreated}"
VerticalOptions="End" />
<Label Grid.Row="1"
Grid.Column="1"
Text="{Binding Category}"
VerticalOptions="End" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
` MainPage.xaml.cs(带列表视图):
`
public partial class MainPage : ContentPage
{
public IList<ExpenseEntry> ExpenseEntries { get; set; }
public MainPage()
{
InitializeComponent();
}
async void OnAddExpenseClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new ExpensesEntryPage());
}
protected override void OnAppearing()
{
ExpenseEntries = (Application.Current as TrackExpensesApp.App).ExpenseEntries;
BindingContext = this;
}
async void ExpenseEntriesItemSelected(object sender, SelectedItemChangedEventArgs e)
{
ExpenseEntry selectedItem = e.SelectedItem as ExpenseEntry;
await Navigation.PushAsync(new ExpensePage());
}
}
`
App.xaml.cs:
`
public partial class App : Application
{
public IList<ExpenseEntry> ExpenseEntries { get; set; }
public IList<string> Categories { get; set; }
public App()
{
InitializeComponent();
// Load in all expenses before loading in the main page
ExpenseEntries = new List<ExpenseEntry>();
Categories = new List<string>();
Categories.Add("Monthly");
Categories.Add("Vacation");
Categories.Add("Other");
MainPage = new NavigationPage(new MainPage());
BindingContext = this;
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
` 如果有人能尽快回复我,我将不胜感激。谢谢!
【问题讨论】:
-
更新列表的代码在哪里?
-
嗨杰森!我以另一种形式更新代码。这是代码。 '(Application.Current as TrackExpensesApp.App).ExpenseEntries.Add(new ExpenseEntry { Name = NameEntry.Text, Category = CategoryPicker.SelectedItem.ToString(), Details = DetailsEditor.Text, StartDate = StartDatePicker.Date, EndDate = EndDatePicker。日期});'
-
使用 ObservableCollection 而不是列表
-
您好!我已经这样做了,但现在我得到一个异常,说无效的演员表。你能帮忙吗?
-
请更新您的问题以包含您修改后的代码,并注意导致异常的 exact 行
标签: c# xaml listview xamarin xamarin.forms