0

I'd like to be able to bind the CommandParameter of a Button to be the current ListViewItem. Here's my XAML :

<ListView Grid.Row="1" x:Name="Playlists" ItemsSource="{Binding Playlists, UpdateSourceTrigger=PropertyChanged}">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel HorizontalAlignment="Center" VerticalAlignment="Top" Width="100" Margin="5">
                <Button x:Name="btnPlayPlaylist" Content="Play" Command="{Binding Path=PlayPlaylistCommand}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

When I click the btnPlayPlaylist button, I'd like to be able to receive in my ViewModel the corresponding playlist. Either by getting it's index in my List<Playlist> or the Playlist object directly.

Is their any way of doing that ?

Thanks :)

2 Answers 2

2

Of course there is. You are using a command, in this case you should define a parameter for it in order for the code behind to have access to the Model in which the button was located.

So briefly:

<Button x:Name="btnPlayPlaylist" Content="Play" Command="{Binding Path=PlayPlaylistCommand}" CommandParameter="{Binding}" />

The command parameter is now the whole Playlist (the whole DataContext of the button). In code behind for Command_Executed, access the parameter like so:

var playlist = e.Parameter as Playlist;

here I assumed that your DataType is Playlist.

NOTE: however there is another approach to this without the use of commands! Just add an event handler for the button and specify a Tag on it.

<Button x:Name="btnPlayPlaylist" Content="Play" Click="button_Click" Tag="{Binding}" />

and then in code behind:

var playlist = (sender as Button).Tag as Playlist;

remember always to Cast the Tag and sender and parameter

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ! I never though it'd be so simple :P
;) With WPF a lot of things are easier.
2

To send current DataContext as CommandParameter you do

<Button ... CommandParameter="{Binding}">

Or

<Button ... CommandParameter="{Binding Path=.}">

1 Comment

@Dpedrinha in this case there's no difference but if you would like to add Converter for example then you need to explicitly set Path and then you need to use second option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.