AntoineB
AntoineB

Reputation: 4694

C# - Bind CommandParameter to the "DataContext" of a ListViewItem

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 :)

Upvotes: 0

Views: 2088

Answers (2)

dkozl
dkozl

Reputation: 33364

To send current DataContext as CommandParameter you do

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

Or

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

Upvotes: 2

uncommon_name
uncommon_name

Reputation: 470

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

Upvotes: 2

Related Questions