2016-01-05 53 views
0

我希望能够将ButtonCommandParameter绑定为当前的ListViewItem。这是我的XAML:C# - 将CommandParameter绑定到ListViewItem的“DataContext”

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

当我点击btnPlayPlaylist按钮,我希望能在我的视图模型来获得相应的播放列表。可以通过直接在我的List<Playlist>Playlist对象中获取索引。

他们有什么办法呢?

谢谢:)

回答

2

当然有。 您正在使用一个命令,在这种情况下,您应该为其定义一个参数,以便后面的代码可以访问该按钮所在的模型。

那么简单:

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

命令参数是现在整个播放列表(按钮的全DataContext的)。 在背后Command_Executed代码,访问参数,如下所示:

var playlist = e.Parameter as Playlist; 

这里我假定你的数据类型是播放列表。

注意:但是,有另一种方法不使用命令!只需为该按钮添加一个事件处理程序并在其上指定一个标记即可。

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

,然后在后面的代码:

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

永远记住铸标签和发件人和参数

+0

谢谢!我从来不会这么简单:P – AntoineB

+0

;)对于WPF,很多事情都比较容易。 –

2

要发送当前DataContext作为CommandParameter你做

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

或者

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

第一个选项适用于我。有什么不同? – Dpedrinha

+0

@Dpedrinha在这种情况下没有什么区别,但是如果你想添加Converter,例如你需要明确设置Path,然后你需要使用第二个选项。 – dkozl