c# - 只需单击 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 中启动函数的最佳方法是什么?
解决方案
ItemSelected
是一个事件,你不能将它绑定到一个方法。我将为您提供有关如何ViewMomdel
通过单击以下项目来启动功能的解决方案ListView
:
在xml中:
<ListView ItemsSource="{Binding Games}" SelectedItem="{Binding SelectedGame}" ItemSelected="ListView_ItemSelected">
在后面的代码中,在方法中获取当前的ViewModel,ListView_ItemSelected
然后调用InsertGame
ViewModel,你也可以传递当前的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;
}
...
}
推荐阅读
- javascript - React hook form failed to submit within react testing library test
- sql - Cakephp 4 Two new columns are not filled even after rebuilding the model from scratch multiple times
- html - 这是什么 CSS 属性:-internal-light-dark
- java - Hibernate @Filter does not work with Spring JpaRepository.findById method
- javascript - Trying to find the binary of 3 items in array. Getting infinite loop
- gatsby - MDX renderer - Gatsby Site -
- ,
and
tags not rendering
- ,
- apache-flink - 如何使用 Apache flink 处理乱序事件?
- python - 找不到使用 Selenium 和 Python 登录 Google 的密码字段
- javascript - ReactJS - 无法在另一个组件中的 DOM 上显示内容
- php - 如何将图标列表小部件(Elementor)居中,图标在左侧对齐?