我刚开始使用Xamarin表单现在我有一个项目列表,我在自定义模板中显示。
我想要的行为是事件在页面上下文中触发(使用Corcav.Behaviors),但我想将单击的项目传递给命令。我似乎无法让最后一部分工作。使用下面的实现,事件正确触发,但传递的参数是MyEventsListModel,但我想要点击的项目。
注意我最好在xaml / viewmodel中使用解决方案,而不是在代码隐藏中。而事件发生的两个事件的替代解决方案也很好。
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:behaviors="clr-namespace:Corcav.Behaviors;assembly=Corcav.Behaviors"
x:Class="TheEventsApp.Mobile.MyEventsList"
Title="My Events"
x:Name="MainPage">
<ListView ItemsSource="{Binding Events}">
<behaviors:Interaction.Behaviors>
<behaviors:BehaviorCollection>
<behaviors:EventToCommand EventName="ItemTapped" Command="{Binding NavigateToEventDetails}" CommandParameter="{Binding .}" />
</behaviors:BehaviorCollection>
</behaviors:Interaction.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical">
<Label Text="{Binding Name}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
视图模型:
[ImplementPropertyChanged]
public class MyEventsListModel : FreshBasePageModel
{
private readonly EventsDatastore eventsStore;
public MyEventsListModel(EventsDatastore eventsStore)
{
this.eventsStore = eventsStore;
}
protected async override void ViewIsAppearing(object sender, EventArgs e)
{
this.Events = await eventsStore.GetMyEventsAsync();
}
public ObservableCollection<Event> Events { get; set; } = new ObservableCollection<Event>();
public Command NavigateToEventDetails
{
get
{
return new Command(async (clickedEvent) =>
{
await CoreMethods.PushPageModel<EventDetailsPageModel>(clickedEvent);
});
}
}
}
答案 0 :(得分:2)
解决方案非常简单。在深入了解Corcav的源代码后,很容易弄明白。 EventToCommand.cs
中的以下代码private void OnFired(EventArgs e)
{
object param = this.PassEventArgument ? e : this.CommandParameter;
if (!string.IsNullOrEmpty(this.CommandName))
{
if (this.Command == null) this.CreateRelativeBinding();
}
if (this.Command == null) throw new InvalidOperationException("No command available, Is Command properly set up?");
if (e == null && this.CommandParameter == null) throw new InvalidOperationException("You need a CommandParameter");
if (this.Command != null && this.Command.CanExecute(param))
{
this.Command.Execute(param);
}
}
处理它。只需设置&#34; PassEventArgument&#34;真的为我解决了这个问题。
<behaviors:EventToCommand EventName="ItemTapped" Command="{Binding NavigateToEventDetails}" PassEventArgument="True" />