经过大量的谷歌搜索后,我还没有找到关于这个问题的答案。 我有这个ListView
<ListView x:Name="itemListView" ItemsSource="{Binding History}" HorizontalAlignment="Stretch">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource Border}" Background="{ThemeResource GradientLinear}" HorizontalAlignment="Stretch">
<Grid>
<StackPanel Orientation="Vertical" Margin="10,10,10,10" HorizontalAlignment="Left" Grid.Row="0" Grid.Column="0">
<TextBlock Text="{Binding name}" />
<TextBlock Text="{Binding question}" TextWrapping="Wrap"/>
<TextBlock Text="{Binding vrijeme}"/>
</StackPanel>
<Button Width="50" Height="50" Opacity="0.6" Grid.Row="0" Grid.Column="1" Tag="{Binding name}"
Command="{Binding ElementName=itemListView, Path=DataContext.Delete}" CommandParameter="{Binding ElementName=itemListView, Path=SelectedIndex}"
HorizontalAlignment="Right">
<SymbolIcon
HorizontalAlignment="Center"
Width="48"
Height="48"
Symbol="Delete" />
</Button>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
问题可能在代码的这一部分
<Button Width="50" Height="50" Opacity="0.6" Grid.Row="0" Grid.Column="1" Tag="{Binding name}"
Command="{Binding ElementName=itemListView, Path=DataContext.Delete}" CommandParameter="{Binding ElementName=itemListView, Path=SelectedIndex}"
HorizontalAlignment="Right">
当我单击Button时,没有选择包含该Button的ListViewItem,因此我获得-1的SelectedIndex,或者如果我定位SelectedItem则为null。似乎单击该按钮不会影响ListViewItem。如果我先单击ListViewItem,然后单击单击,它就会起作用,当然,SelectedItem是在ListView中设置的,但是我不能认为用户会理解这一点。我的问题是-有什么方法可以在CommandArgument SelectedItem或SelectedIndex中“强制”按钮发送给我。我知道如何通过代码隐藏来做到这一点,但我有兴趣通过MVVM解决此问题。 谢谢。