Question

Iam using MVVMlight for windows 8.1 app. I want to navigate to a new view when list Item is clicked and pass the clicked item as parameter.

I have defined An attached property like:

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);
    }
}

The xaml in the view looks like:

<GridView
                        ItemsSource="{Binding Source={StaticResource ItemsSource}}"
                        ItemTemplate="{StaticResource itemsTemplate}"
                        SelectionMode="None"
                        helpers:ItemClickCommand.Command="{Binding ItemClicked}"
                        >
                    </GridView>

And the view model:

private RelayCommand<Item> _ItemClicked;
    public RelayCommand<Item> ItemClicked 
    {
        get 
        {
            if (_ItemClicked == null)
            {
                _ItemClicked = new RelayCommand<Item>(
                    (item) =>
                    {
                        _navigationService.Navigate(typeof(ItemsPage));
                    });
            }

            return _ItemClicked;
        }        
    }

Nothing happens when I click the Grid Item.

Was it helpful?

Solution

I resorted to this tutorial by: Laurent Bugnion

http://msdn.microsoft.com/en-us/magazine/dn237302.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top