简体   繁体   中英

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

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

To send current DataContext as CommandParameter you do

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

Or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM