首页 > 解决方案 > 只需单击 ListView 中的项目,在 ViewMomdel 中启动函数的最佳方法是什么

问题描述

我想在单击项目时立即将 ListView 中所选项目的数据添加到几个条目中。

我的 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:local="clr-namespace:WishListProject.ViewModels"
             x:Class="WishListProject.Views.UpdateGames">

    <ContentPage.BindingContext>
        <local:GameListViewModel />
    </ContentPage.BindingContext>

    <ContentPage.Content>
        <StackLayout>
            <ListView ItemsSource="{Binding Games}" SelectedItem="{Binding SelectedGame}" ItemSelected="{Binding InsertGame }">
            </ListView>
            <Entry Placeholder="ID" IsVisible="False" Text="{Binding IdEntry}"></Entry>
            <Entry Placeholder="GameName" Text="{Binding GameNaamEntry}"></Entry>
            <Entry Placeholder="GameGenre" Text="{Binding GameGenreEntry}"></Entry>
            <Entry Placeholder="GameRelease" Text="{Binding GameReleaseEntry}"></Entry>
            <Button Text="Update Game" Command="{Binding UpdateGameCommand}" />

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

这是我要启动的功能,用于使用 VIEWMODEL 将所选项目数据显示到几个条目中:

public void InsertGame(object sender, SelectedItemChangedEventArgs e)
        {
            Game game = new Game(); 
            game = SelectedGame;
            IdEntry.Text = game.Id.ToString();
            GameNaamEntry = game.GameNaam;
            GameGenreEntry = game.GameGenre;
            GameReleaseEntry = game.GameRelease;
        }

只需单击 ListView 中的项目,在 VIEWMODEL 中启动函数的最佳方法是什么?

标签: c#xamarin

解决方案


ItemSelected是一个事件,你不能将它绑定到一个方法。我将为您提供有关如何ViewMomdel通过单击以下项目来启动功能的解决方案ListView

在xml中:

<ListView ItemsSource="{Binding Games}" SelectedItem="{Binding SelectedGame}" ItemSelected="ListView_ItemSelected">

在后面的代码中,在方法中获取当前的ViewModel,ListView_ItemSelected然后调用InsertGameViewModel,你也可以传递当前的selectedGame

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        Game selectedGame = e.SelectedItem as Game;
        var currentVm = this.BindingContext as GameListViewModel;
        currentVm.InsertGame(selectedGame);
    }
}

还有你的 ViewModel:

public class GameListViewModel : INotifyPropertyChanged
{
    public void InsertGame(Game currentGame)
    {
        GameNaamEntry = currentGame.GameNaam;
    }
    ...
}

推荐阅读