【问题标题】:WPF SelectedItem passed as a command parameter doesn't return value作为命令参数传递的 WPF SelectedItem 不返回值
【发布时间】:2017-10-21 09:21:58
【问题描述】:
<ScrollViewer VerticalScrollBarVisibility="Auto">
        <ListBox x:Name="RootListView" ItemsSource="{Binding Ratings}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid ShowGridLines="True">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="auto" />
                            <RowDefinition Height="auto" />
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="40" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>     

                         .... Some TextBoxes with Labels are here to fill the grid .....

                        <Button  Grid.Row="4" Grid.Column="1" Content="Delete" 
                                 Command="{Binding ElementName=RootListView, Path=DataContext.DeleteRatingCommand}"
                                 CommandParameter="{Binding ElementName=RootListView, Path=SelectedItem}">

                        </Button>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
 </ScrollViewer>

Ratings 在我的视图模型中的位置是:

public ObservableCollection<RatingModel> Ratings;

DeleteRatingCommand 是一个ICommand 对象。

在这个视图中显示了一个完整的评分集合(一个包含信息的网格),每个都有一个删除按钮。当按下相应评级的按钮时,我想将评级对象发送到具有SelectedItem 属性的视图模型。尽管调用了绑定方法,但没有通过 SelectedItem 参数传递任何内容,特别是 null 值。在这种情况下,如何正确使用SelectedItem 向视图模型发送有关要删除哪个评级的信息?还有其他可能吗?我不确定这种方法是否正确。

【问题讨论】:

    标签: c# wpf listbox selecteditem


    【解决方案1】:

    我假设单击按钮实际上并未设置 SelectedItem 属性。

    尝试将绑定更改为行上下文数据。

    CommandParameter="{Binding Path=.}"
    

    【讨论】:

    • 这正是我想出的。您甚至可以将其简化为CommandParameter="{Binding}"
    最近更新 更多