[英]How can I bind a ViewModel to an XAML file inside a ListView of another XAML file?
我確實不確定該如何搜索,所以我希望有人可以理解我的問題,並幫助或闡明我的方法是否不正確。
我有2個XAML文件( ItemsPage和ItemTemplatePage ),我想將每個XAML文件綁定到ViewModel( ItemsPageViewModel和ItemTemplateViewModel )-現在,當它們都是單獨的頁面時,這很簡單,但是在此示例中,ItemTemplatePage加載到ItemsItem中每個項目的ItemsPage上的ListView。
顯然,當我與Item交互時,我將在后面為ItemTemplatePage調用代碼,但我寧願為ItemTemplateViewModel調用Command。 但是,當Items填充並綁定到ItemsPage中的ListViews ItemsSource時,據我了解,這會為該特定模板創建Item的BindingContext。 因此,這不像我可以在ItemTemplatePage的構造函數中調用的那樣:
BindingContext = new ItemTemplateViewModel();
因為此時它會覆蓋ItemsSource從ItemsPage完成的所有綁定; 至少那是我到目前為止所經歷的。
下面是到目前為止我可以從代碼的角度理解的代碼,是我試圖實現可行的代碼,還是讓我自己變得復雜,或者我誤解了Binding,而我的方法是完全錯誤的?
任何幫助都將受到高度贊賞!
===
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的代碼,因為這里沒有編寫其他代碼。
ListView
實現DataTemplate
,這意味着它的內容綁定到項目,而不是一般地綁定到頁面視圖模型,這就是它應該工作的方式,如果您嘗試提供任何其他綁定上下文,它不會使應用程序崩潰,但是可以肯定應用程序將無法正常運行,因為您基本上會以這種方式違反XAML邏輯。
同樣,您的ItemTemplagePage
根本不是(也不應該是)頁面,但是由於某種原因,您將其稱為頁面,這可能會使您進一步困惑。
總的來說,您需要做更多的工作才能了解XAML中的一些基本術語和原理。 我想您想檢查是否正確,這很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.