wpf 命令参数 Datagrid SelectedItems 为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29038064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:00:42  来源:igfitidea点击:

Command Parameter Datagrid SelectedItems is null

wpfmvvmbindingdatagridcommandparameter

提问by chris

So I found this answer Pass command parameter from the xamlwhich I think got me most of the way there. The problem I am having is when I select a row in the datagrid it triggers the command but the selected items is null.

所以我从 xaml 中找到了这个答案Pass 命令参数,我认为它让我在那里得到了大部分。我遇到的问题是,当我在数据网格中选择一行时,它会触发命令,但所选项目为空。

What I don't know, and suspect is the issue, is what type should I be passing the selecteditems to in the view model? Currently I am using IList as shown in my viewmodel code:

我不知道,并且怀疑是问题,我应该在视图模型中将 selecteditems 传递给什么类型?目前我正在使用 IList,如我的视图模型代码所示:

namespace Project_Manager.ViewModel
{
public class ProjectSummaryViewModel : ObservableObject
{
    public ProjectSummaryViewModel()
    {
        ProjectSummary = DatabaseFunctions.getProjectSummaryData();
    }

    private ObservableCollection<ProjectSummaryModel> projectsummary;
    public ObservableCollection<ProjectSummaryModel> ProjectSummary
    {
        get { return projectsummary; }
        set
        {
            projectsummary = value;
            OnPropertyChanged("ProjectSummary");
        }
    }

    public ICommand DeleteRowCommand
    {
        get { return new ParamDelegateCommand<IList<ProjectSummaryModel>>(DeleteRow); }
    }

    private void DeleteRow(IList<ProjectSummaryModel> projectsummaryselected)
    {
        string name = projectsummaryselected[0].ProjectName;
    }
}
}

The XAML view code for the datagrid looks like this:

数据网格的 XAML 视图代码如下所示:

<Window x:Class="Project_Manager.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">

<!--<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Window.Resources>-->

    <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/> <!--Menu row-->
        <RowDefinition Height="Auto"/> <!--button row-->
        <RowDefinition/> <!--Current projects-->
        <RowDefinition/> <!--Completed projects-->
    </Grid.RowDefinitions>

    <!--<Menu>
        <MenuItem Header="File">
            <MenuItem Header="New Project Management" CommandTarget="{Binding NewTable}"/>
            <MenuItem Header="Open Project Management"/>
            <Separator/>
            <MenuItem Header="Exit"/>
        </MenuItem>
        <MenuItem Header="View">
            <MenuItem x:Name="ViewCompleted" IsCheckable="True" IsChecked="True" Header="View Completed Projects List"/>
        </MenuItem>
        <MenuItem Header="Project Management">
            <MenuItem Header="New Project"/>
        </MenuItem>

    </Menu>-->

    <StackPanel Grid.Row="1" Orientation="Horizontal">
        <Button Content="Create New Project" Command="{Binding Path=NewProjectCommand}"/>
        <!--<Button Content="View Details" Visibility="{Binding Source={x:Reference Name=CurrentProjectsDataGrid}, Path=IsSelected, Converter={StaticResource BooleanToVisibilityConverter}}"/>-->
    </StackPanel>

    <Grid Grid.Row="2">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Text="Current Projects" Background="LemonChiffon"/>
        <DataGrid x:Name="SummaryDataGrid" ItemsSource="{Binding ProjectSummary}" Grid.Row="1" AutoGenerateColumns="True" Style="{StaticResource DataGridStyle}">
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Delete Row" Command="{Binding DeleteRowCommand}" CommandParameter="{Binding SelectedItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>
    </Grid>


    <!--<DataGrid.Columns>
                <DataGridTextColumn Header="Project Name" Binding=""/>
                <DataGridTextColumn Header="Team Name"/>
                <DataGridTextColumn Header="Latest Update"/>
                <DataGridTextColumn Header="Date Started"/>
            </DataGrid.Columns>-->

    <!--<Grid Grid.Row="3">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        --><!--<TextBlock Text="Completed Projects" Background="LightGreen" Visibility="{Binding Source={x:Reference Name=ViewCompleted}, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"/>
        <DataGrid Grid.Row="1" AutoGenerateColumns="False" Style="{StaticResource DataGridStyle}" Visibility="{Binding Source={x:Reference Name=ViewCompleted}, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Project Name"/>
                <DataGridTextColumn Header="Team"/>
                <DataGridTextColumn Header="Date Completed"/>
            </DataGrid.Columns>
        </DataGrid>--><!--
    </Grid>-->
</Grid>

And just in case this is a command implementation problem here is the custom Delegate Command that I am using:

以防万一这是一个命令实现问题,这里是我正在使用的自定义委托命令:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace Project_Manager.Common
{
public class ParamDelegateCommand<T> : ICommand
{
    public event EventHandler CanExecuteChanged;

    private Action<T> executeMethod;

    //private Func<T, bool> canExecuteMethod;

    public ParamDelegateCommand(Action<T> executeMethod) //, Func<T, bool> canExecuteMethod)
    {
        this.executeMethod = executeMethod;
        //this.canExecuteMethod = canExecuteMethod;
    }

    public bool CanExecute(object parameter)
    {
        return true; //canExecuteMethod((T)parameter);
    }

    public void Execute(object parameter)
    {
        executeMethod((T)parameter);
    }
}
}

I have searched around and can find plenty of examples for the XAML binding I just can't seem to find the other half of it. So what type should be in the viewmodel? Alternatively what is the actual problem?

我四处搜索,可以找到很多 XAML 绑定的示例,但我似乎找不到它的另一半。那么viewmodel中应该是什么类型呢?或者,实际问题是什么?

Edit: Just noticed an error the debug window that might help someone

编辑:刚刚注意到一个错误,可能对某人有帮助的调试窗口

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=SelectedItems; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'CommandParameter' (type 'Object')

System.Windows.Data 错误:4:无法找到引用“RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''的绑定源。BindingExpression:Path=SelectedItems; 数据项=空;目标元素是 'MenuItem' (Name=''); 目标属性是“CommandParameter”(类型“Object”)

回答by Ayyappan Subramanian

If you are using context menu please refer the below code to get SelectedItems.

如果您使用上下文菜单,请参考以下代码以获取 SelectedItems。

<ContextMenu>
    <MenuItem Header="Delete Row" Command="{Binding DeleteRowCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItems}"/>
</ContextMenu>

Also Selecteditems is an IList so change the code like below.

Selecteditems 也是一个 IList,因此更改如下代码。

public ICommand DeleteRowCommand
{
    get { return new ParamDelegateCommand<IList>(DeleteRow); }
}

private void DeleteRow(IList projectsummaryselected)
{
    string name = (projectsummaryselected[0] as ProjectSummaryModel).ProjectName;
}

回答by Muds

Try this

尝试这个

<MenuItem Header="Delete Row" Command="{Binding DeleteRowCommand}" CommandParameter="{Binding SelectedItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"/>