我在Windows 8.1应用程序中使用MVVMlight。我想在单击列表项时导航到新视图,并将单击的项目作为参数传递。
我已经定义了一个附加属性,如:
public static class ItemClickCommand
{
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand),
typeof(ItemClickCommand), new PropertyMetadata(null, OnCommandPropertyChanged));
public static void SetCommand(DependencyObject d, ICommand value)
{
d.SetValue(CommandProperty, value);
}
public static ICommand GetCommand(DependencyObject d)
{
return (ICommand)d.GetValue(CommandProperty);
}
private static void OnCommandPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var control = d as ListViewBase;
if (control != null)
control.ItemClick += OnItemClick;
}
private static void OnItemClick(object sender, ItemClickEventArgs e)
{
var control = sender as ListViewBase;
var command = GetCommand(control);
if (command != null && command.CanExecute(e.ClickedItem))
command.Execute(e.ClickedItem);
}
}
视图中的xaml如下所示:
<GridView
ItemsSource="{Binding Source={StaticResource ItemsSource}}"
ItemTemplate="{StaticResource itemsTemplate}"
SelectionMode="None"
helpers:ItemClickCommand.Command="{Binding ItemClicked}"
>
</GridView>
视图模型:
private RelayCommand<Item> _ItemClicked;
public RelayCommand<Item> ItemClicked
{
get
{
if (_ItemClicked == null)
{
_ItemClicked = new RelayCommand<Item>(
(item) =>
{
_navigationService.Navigate(typeof(ItemsPage));
});
}
return _ItemClicked;
}
}
单击网格项时没有任何反应。