【发布时间】:2019-07-24 10:30:35
【问题描述】:
我真的不确定如何搜索这个,所以我希望有人能理解我的问题,并帮助或澄清我的方法是否不正确。
我有 2 个 XAML 文件(ItemsPage 和 ItemTemplatePage),我想将每个 XAML 文件绑定到一个 ViewModel(ItemsPageViewModel 和ItemTemplateViewModel) - 现在,当它们都是单独的页面时,这很简单,但在此示例中,ItemTemplatePage 被加载到 ItemsPage 上的 ListView 中,用于 Items 中的每个项目。
显然,当我与一个项目交互时,我会为 ItemTemplatePage 调用后面的代码,但我宁愿为 ItemTemplateViewModel 调用一个命令。但是,当 Items 填充并绑定到 ItemsPage 中的 ListViews ItemsSource 时,据我所知,它会为该特定模板创建 Item 的 BindingContext。所以我不能在 ItemTemplatePage 的构造函数中调用:
BindingContext = new ItemTemplateViewModel();
因为此时它会覆盖 ItemsSource 从 ItemsPage 完成的任何绑定;至少这是我迄今为止所经历的。
以下是迄今为止我从代码的角度提供理解的代码,是我试图实现的目标,还是我自己让它变得复杂,或者我误解了绑定,我的方法是完全错了吗?
非常感谢任何和所有帮助!
===
ItemsPage.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:template="clr-namespace:App.Views.Templates"
x:Class="App.Views.ItemsPage"
Title="All Items">
<ContentPage.Content>
<StackLayout>
<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<template:Item />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Contant>
</ContentPage>
ItemsPage.xaml.cs
Public ItemsPage() {
InitializeComponent();
BindingContext = new ItemsPageViewModel();
}
ItemsPageViewModel.cs
public class ItemsPageViewModel : BaseViewModel {
private ObservableCollection<Item> items;
public ObservableCollection<Item> Items { get => items; set => SetValue(ref items, value); }
public ItemsPageViewModel() => DownloadItems();
private async void Download() => Items = await API.GetItems();
}
ItemTemplagePage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="App.Views.Templates.ItemTemplatePage"
Spacing="0">
<Label Text="{Binding Name}" />
<Button Text="View" />
</StackLayout>
我没有提供 ItemTemplatePage.xaml 背后的代码,因为这里没有编写额外的代码。
【问题讨论】:
标签: c# xaml listview xamarin xamarin.forms