【问题标题】:use of selectedindex in datagrid wpf在datagrid wpf中使用selectedindex
【发布时间】:2014-07-31 10:45:42
【问题描述】:

我正在使用 mvvm light 学习 wpf,但我遇到了一个问题。 我有一个用户控件,其中包含一个加载了查询的数据网格。

现在我想在 selectedIndex 上添加一个事件来检索选定的行,然后我会将值传递给其他用户控件。

问题是我的事件从未被触发。

这就是我所做的

<DataGrid HorizontalAlignment="Left" Name="dgUser" VerticalAlignment="Top" SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}" SelectedItem="{Binding selectedRow, Mode=TwoWay}"  Width="800" Height="253" >

这是我的视图模型的代码

public RelayCommand selectedRow { get; private set; }
    private int _selectedIndex;
    public int SelectedIndex
    {
        get { return _selectedIndex; }
        set
        {
            _selectedIndex = value;
            RaisePropertyChanged("SelectedIndex");
        }
    }
    /// <summary>
    /// Initializes a new instance of the ListUserViewModel class.
    /// </summary>
    public ListUserViewModel()
    {
        selectedRow = new RelayCommand(() => SelectedRowChange());
        SelectedIndex = 2;
    }

    private void SelectedRowChange()
    {
        System.Windows.MessageBox.Show("test");
    }

我的行没有被 SelectedXIndex = 2 选中 当我选择另一行时没有任何反应

【问题讨论】:

  • SelectedItem 不是事件,而是属性。 SelectionChanged 是事件。尝试使用它。
  • selectionChanged 抛出异常,除非我使用 EventTrigger

标签: wpf binding datagrid mvvm-light selectedindex


【解决方案1】:

您正在尝试将 ViewModel 上的 Command 绑定到 DataGrid 的 SelectedItem ,但这不是它的工作原理。

您想挂接到DataGrid.SelectionChanged 事件并大概在此时触发您的ViewModel 的RelayCommand

Check this answer 很好地解释了如何在 XAML 中执行此操作。

编辑:

要将SelectedItem 作为命令参数传递给您的RelayCommand,请在您的 XAML 中使用以下内容:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
        <i:InvokeCommandAction Command="{Binding MyCommand}" 
        CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

并确保您将RelayCommand 更改为您希望的类型。

注意:您还没有提供您在DataGrid 中的项目类型,所以我将在此处使用object

public RelayCommand<object> selectedRow { get; private set; }

然后您可以依赖命令的参数作为选定项:

public ListUserViewModel()
{
    selectedRow = new RelayCommand(i => SelectedRowChange(i));
    SelectedIndex = 2;
}

private void SelectedRowChange(object selectedItem)
{
    // selectedItem is the item that has just been selected
    // do what you wish with it here
    System.Windows.MessageBox.Show("test");
}

【讨论】:

  • 感谢我使用 EventTrigger 并且我的事件是用消息框触发的,但是我怎样才能获得所选行的值?
  • 您可以通过该帖子中的其他示例将SelectedItem 作为参数传递给您的RelayCommand。如果这回答了您的问题,请点击左侧的绿色勾号。
  • 你能解释一下如何使用命令参数吗?我的行不是来自模型,而是来自 query.tolist()
  • 已更新。如果您还有其他问题,请提出其他问题。
  • 命令参数。 RelayCommand&lt;object&gt;。如果您不了解这一点,则需要阅读有关 WPF 和 MVVM Light 的更多信息。
猜你喜欢
  • 2014-04-17
  • 2012-11-28
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多