Question

I have looked all over for an answer to this with no luck. I'm using MVVM Light and I have a ListView in one of my views. I would like to find a way to fire a command when the selected item in my ListView is clicked using the 'Event to Command' built into MVVM Light. At this point, I have no clue how to go about doing this. Any help you could give me would be greatly appreciated.

From my GameView.xaml

<ListView ItemsSource="{Binding Adventurers}"
              Name="AdvListView"
              ScrollViewer.CanContentScroll="False"
              Background="Gray"
              BorderBrush="Transparent"
              Grid.Column="1"
              Grid.ColumnSpan="3"
              Grid.Row="2">

        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <cmd:EventToCommand Command="{Binding ShowAdvCommand}"
                                    CommandParameter="{Binding SelectedItem,
                                          ElementName=AdvListView}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

        <ListView.View>
            <GridView>
                <GridViewColumn Width="Auto" Header="Name" DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn Width="Auto" Header="Level" DisplayMemberBinding="{Binding Level}"/>
            </GridView>
        </ListView.View>
    </ListView>

I'm not entirely sure where in the ListView the EventToCommand should go. Also, I understand that this code is completely incorrect.

From GameViewModel.cs

public ICommand ShowAdvCommand { get; private set; }
ShowAdvCommand = new RelayCommand(() => ExecuteShowAdvCommand(), () => true);

private void ExecuteShowAdvCommand()
{
    System.Windows.MessageBox.Show("Firing");
}
Était-ce utile?

La solution

In the XAML you are subscribing to the Clicked event. Change to the SelectionChanged event to make sure there is a SelectedItem.

A click on the ListView will not always select an item.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top