C#-将CommandParameter绑定到";“数据上下文”;ListViewItem的
我希望能够将C#-将CommandParameter绑定到";“数据上下文”;ListViewItem的,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,我希望能够将按钮的命令参数绑定为当前的列表视图项。这是我的XAML: <ListView Grid.Row="1" x:Name="Playlists" ItemsSource="{Binding Playlists, UpdateSourceTrigger=PropertyChanged}"> <ListView.ItemsPanel> <ItemsPanelTemplate> <WrapPanel /&
按钮的命令参数
绑定为当前的列表视图项
。这是我的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>
当我单击btnPlayPlaylist
按钮时,我希望能够在我的ViewModel中接收相应的播放列表。通过在我的列表
中获取它的索引,或者直接在播放列表
对象中获取它的索引
他们有办法做到这一点吗
谢谢:)当然有。
您正在使用一个命令,在这种情况下,您应该为它定义一个参数,以便代码能够访问按钮所在的模型
简而言之:
<Button x:Name="btnPlayPlaylist" Content="Play" Command="{Binding Path=PlayPlaylistCommand}" CommandParameter="{Binding}" />
这里我假设您的数据类型是Playlist
注意:但是,还有另一种方法不使用命令!只需为按钮添加一个事件处理程序并在其上指定一个标记
<Button x:Name="btnPlayPlaylist" Content="Play" Click="button_Click" Tag="{Binding}" />
请记住始终强制转换标记、发送者和参数当然有。
您正在使用一个命令,在这种情况下,您应该为它定义一个参数,以便代码能够访问按钮所在的模型
简而言之:
<Button x:Name="btnPlayPlaylist" Content="Play" Command="{Binding Path=PlayPlaylistCommand}" CommandParameter="{Binding}" />
这里我假设您的数据类型是Playlist
注意:但是,还有另一种方法不使用命令!只需为按钮添加一个事件处理程序并在其上指定一个标记
<Button x:Name="btnPlayPlaylist" Content="Play" Click="button_Click" Tag="{Binding}" />
请记住,始终强制转换标记、发送者和参数,以便像您所做的那样发送当前的DataContext
<Button ... CommandParameter="{Binding}">
或
以CommandParameter
的方式发送当前的DataContext
<Button ... CommandParameter="{Binding}">
或
谢谢!我从来没想到会这么简单:P;)有了WPF,很多事情都变得简单了。谢谢!我从来没想到会这么简单:P;)有了WPF,很多事情就更容易了。@Dpedrinha在本例中没有区别,但如果您想添加转换器,例如,则需要显式设置路径,然后需要使用第二个选项。@Dpedrinha在本例中没有区别,但如果您想添加转换器,例如,则需要显式设置路径和然后您需要使用第二个选项。