Xamarin基础MasterDetail页面如何实现选中项数据绑定?
Got it, let's walk through how to get that selected item showing up in the detail page using the default MasterDetail template from Visual Studio. I’ve tinkered with this exact setup before, so here’s a straightforward breakdown:
1. Verify the Selected Item Property in Your Main ViewModel
First, head to your ItemsViewModel (the one backing the master list page). Make sure there’s a bindable SelectedItem property that triggers navigation with the item’s ID. If the default code doesn’t pass the ID, update it like this:
private Item _selectedItem; public Item SelectedItem { get => _selectedItem; set { SetProperty(ref _selectedItem, value); if (value != null) { // Pass the item ID as a query parameter when navigating await Shell.Current.GoToAsync($"{nameof(ItemDetailPage)}?{nameof(ItemDetailViewModel.ItemId)}={value.Id}"); SelectedItem = null; // Clear selection after navigation } } }
Note: Your Item class (from the template) should already have Id, Text, and Description properties—if not, add them with INotifyPropertyChanged support, though the default template includes this.
2. Update the Detail ViewModel to Receive the Item
Next, open ItemDetailViewModel. The default version might be empty, so we’ll add code to fetch the selected item using the ID passed from the master page. Use the [QueryProperty] attribute to automatically grab the ID from the navigation URL:
[QueryProperty(nameof(ItemId), nameof(ItemId))] public class ItemDetailViewModel : BaseViewModel { private string _itemId; public string ItemId { get => _itemId; set { _itemId = value; LoadSelectedItem(value); } } public Item Item { get; set; } async void LoadSelectedItem(string itemId) { try { // Fetch the item from the mock data store (default template has this) var item = await DataStore.GetItemAsync(itemId); Item = item; OnPropertyChanged(nameof(Item)); // Ensure UI updates } catch (Exception ex) { // Add simple error handling here (e.g., show an alert) Console.WriteLine($"Failed to load item: {ex.Message}"); } } }
The DataStore is part of the default template—it’s a mock service that returns items from a list. If you’re using a real database, replace this call with your data fetch logic.
3. Bind the Detail Page UI to the Selected Item
Now open ItemDetailPage.xaml—this is where we’ll replace the empty layout with elements bound to the Item property in the view model. Update the XAML like this:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourAppNamespace.ItemDetailPage" Title="{Binding Item.Text}"> <!-- Set page title to the item's text --> <ScrollView Padding="20,30"> <StackLayout Spacing="15"> <!-- Item Text Section --> <Label Text="Item Name:" FontAttributes="Bold" FontSize="Subtitle" /> <Label Text="{Binding Item.Text}" FontSize="Large" TextColor="DarkBlue" /> <!-- Item Description Section --> <Label Text="Description:" FontAttributes="Bold" FontSize="Subtitle" /> <Label Text="{Binding Item.Description}" FontSize="Medium" /> </StackLayout> </ScrollView> </ContentPage>
Make sure the BindingContext of the detail page is set to ItemDetailViewModel—the default template should already do this in the page’s constructor, but double-check:
public ItemDetailPage() { InitializeComponent(); BindingContext = new ItemDetailViewModel(); }
4. Test It Out
Run your app now—when you select an item from the master list, the detail page should load and display the item’s text and description automatically. If something doesn’t work, double-check:
- That
ItemimplementsINotifyPropertyChanged(default template includes this viaBaseViewModel) - That the navigation URL is correctly passing the
ItemId - That the
DataStore.GetItemAsyncmethod is returning the correct item for the given ID
内容的提问来源于stack exchange,提问作者RandomString

