经过一番谷歌搜索后,我还没有找到关于这个问题的答案。我有这个 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,因此 SelectedIndex 为 -1,如果我以 SelectedItem 为目标,则为 null。似乎单击该按钮会使包含 ListViewItem 不受影响。如果我首先单击 ListViewItem 并且单击按钮它起作用,则 SelectedItem 当然是在 ListView 中设置的,但我不能指望用户会理解这一点。我的问题是 - 有什么方法可以“强制”按钮将 CommandArgument SelectedItem 或 SelectedIndex 发送给我。我知道如何通过代码隐藏来做到这一点,但我有兴趣通过 MVVM 解决这个问题。提前谢谢。