C# 单击ListView中的项在ViewMomdel中启动函数的最佳方式是什么
我想在单击项目时立即将列表视图中所选项目的数据添加到几个条目中 我的XAML代码:C# 单击ListView中的项在ViewMomdel中启动函数的最佳方式是什么,c#,xamarin,C#,Xamarin,我想在单击项目时立即将列表视图中所选项目的数据添加到几个条目中 我的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-na
<?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>
单击ListView中的项在VIEWMODEL中启动函数的最佳方法是什么?您可以在设置
SelectedItem
时调用您的方法。由于您使用的是绑定,我假设您的视图模型中有类似的内容:
Game _selectedGame;
public Game SelectedGame
{
get { return _selectedGame; }
set {
SetProperty(ref _selectedGame, value);
// code to add in the setter
if (value != null)
InsertGame();
//----------------------------
}
}
只需确保在属性更改后调用该方法即可
然后,您还需要将方法签名简化为:
public void InsertGame(){
...
}
你应该准备好了
快乐编码 ItemSelected
是一个事件,不能将其绑定到方法。我将为您提供一个关于如何在viewmodel
中启动函数的解决方案,只需单击列表视图中的项目即可:
在xaml中:
<ListView ItemsSource="{Binding Games}" SelectedItem="{Binding SelectedGame}" ItemSelected="ListView_ItemSelected">
以及您的ViewModel:
public class GameListViewModel : INotifyPropertyChanged
{
public void InsertGame(Game currentGame)
{
GameNaamEntry = currentGame.GameNaam;
}
...
}
我认为您的问题名称与您的问题正文不匹配。这是我在尝试通过单击listview中的项目启动函数时遇到的错误。您只能绑定到一个而不是一个方法。但是ItemSelected是一个事件。因此,您要么需要在代码隐藏中编写处理程序,要么需要在vm中的SelectedGame中添加一个。您需要使用类似于EventToCommand
helpers的工具,以便与MVVM保持一致。您可以编写自己的行为
或使用所描述的现有行为无需走这么远,有一个简单的方法。看看我的答案。
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);
}
}
public class GameListViewModel : INotifyPropertyChanged
{
public void InsertGame(Game currentGame)
{
GameNaamEntry = currentGame.GameNaam;
}
...
}