我正在使用Prism Library和Xamarin Forms并尝试使用描述here的EventToCommandBehavior将ListTapped行为附加到Listview上。
执行ItemTappedCommand委托时,事件参数为null,这意味着我无法提取ListView项。
以下是我的ViewModel代码:
private DelegateCommand<ItemTappedEventArgs> _itemTappedCommand;
public RecipeListViewModel(INavigationService navigationService) : base(navigationService)
{
RefreshDataCommand = new Command(async () => await RefreshData());
_itemTappedCommand = new DelegateCommand<ItemTappedEventArgs>(args => {
var b = args; // args is null
_navigationService.NavigateAsync(nameof(Recipe));
});
}
public DelegateCommand<ItemTappedEventArgs> ItemTappedCommand { get { return _itemTappedCommand; } }
这是我的XAML
<ListView ItemsSource="{Binding Recipes}"
HasUnevenRows="false"
IsPullToRefreshEnabled="true"
CachingStrategy="RecycleElement"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
RefreshCommand="{Binding RefreshDataCommand}"
x:Name="lvRecipes">
<ListView.Behaviors>
<b:EventToCommandBehavior EventName="ItemTapped" Command="{Binding ItemTappedCommand}" />
</ListView.Behaviors>
<ListView.Header>..........
.....</ListView>
答案 0 :(得分:6)
正如布莱恩所说,你说错了。例如,假设我有一个字符串集合只是为了简化它,但它可以是任何东西的集合。
public class MainPageViewModel
{
public MainPageViewModel()
{
People = new ObservableRangeCollection<string>()
{
"Fred Smith",
"John Thompson",
"John Doe"
};
ItemTappedCommand = new DelegateCommand<string>(OnItemTappedCommandExecuted);
}
public ObservableRangeCollection<string> People { get; set; }
public DelegateCommand<string> ItemTappedCommand { get; }
private void OnItemTappedCommandExecuted(string name) =>
System.Diagnostics.Debug.WriteLine(name);
}
我的ListView只需要执行以下操作:
<ListView ItemsSource="{Binding People}">
<ListView.Behaviors>
<b:EventToCommandBehavior Command="{Binding ItemTappedCommand}"
EventName="ItemTapped"
EventArgsParameterPath="Item" />
</ListView.Behaviors>
</ListView>
ViewModel中的命令应该期望您绑定到ItemsSource
的{{1}}的集合中的确切Object类型。要正确使用它,您只需在ListView
中指定路径,在这种情况下只需EventArgs
。
答案 1 :(得分:2)
Control EventArgs不会传递给ViewModel。这打破了MVVM模式。只需使用EventArgsParameterPath或EventArgsConverter即可将您所需的内容准确传递给ViewModel。