2016-01-05 54 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