【发布时间】:2021-10-19 08:21:34
【问题描述】:
我正在尝试为最近查看的项目创建列表视图。这将在主页上
HomePage.xaml
<ListView x:Name="recentKeyList" ItemsSource="{x:Static local:HomePage.RecentKeysList}" CachingStrategy="RetainElement"
x:FieldModifier="public">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding KeyName}" TextColor="Black" Detail="Subtext" DetailColor="{StaticResource Primary}" Tapped="RecentItem_Tapped"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
HomePage.Xaml.Cs 将使用 KeysPage 中的 getter 方法
static KeysPage KeysPageList = new KeysPage();
public static ObservableCollection<Key> RecentKeysList = KeysPageList.GetList;
将在此列表视图中显示的项目将来自不同的页面(键页面),具体取决于是否被点击。
KeysPage.Xaml.cs
public ObservableCollection<Key> RecentKeys = new ObservableCollection<Key>();
public HomePage HomePageList = new HomePage();
public ObservableCollection<Key> GetList {
get
{
return RecentKeys;
}
set
{
RecentKeys = value;
}
}
private async void Key_Tapped(object sender, ItemTappedEventArgs e)
{
if (listView.SelectedItem == null)
return;
Key p = e.Item as Key;
RecentKeys.Add(p); //Where we add to the observable collection
HomePageList.recentKeyList.ItemsSource = RecentKeys;
}
所以基本上我想做的是:
当从列表视图中选择一个项目时,在 KeysPage 上,将其添加到 ObservableCollection(整个 Key 对象),然后在主页中创建一个对象,该对象调用 Homepage.xaml.cs 中的 GetList 方法并显示该可观察集合在我的列表视图中,但当前显示为空。
【问题讨论】:
-
像这样将两个页面紧密耦合在一起是一个非常糟糕的设计
-
好吧,我是 Xamarin 的新手,所以如果我想创建这种根据项目在主页上显示最近查看的项目的概念,我不确定哪种方法适合点击了另一个页面。
-
有很多方法可以做到这一点 - 最简单的可能是在 App 类中创建一个RecentItems 集合,在 Keys 页面中更新它并在 Home 页面中读取它
-
例如,在我的 App.xaml.cs 中,我会使用
public ObservableCollection<Key> RecentKeys = new ObservableCollection<Key>();,然后我会在 HomePage.xaml.cs 中执行var app = new App(); app.RecentKeys.Add(p);之类的操作,然后执行recentKeyList.ItemsSource = app.RecentKeys;?跨度> -
你必须强制转换才能访问自定义属性 -
((App)App.Current).MyCustomProperty
标签: listview xamarin observablecollection