1

我有一个数据网格,我用数据库中的数据填充。当我单击一行时,我调用 GotFocus 方法并尝试在满足某些要求时使按钮可见。

private void dtgVerkoopsdocumenten_GotFocus(object sender, RoutedEventArgs e)
{
    DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];
    if (row.soort2 == "Factuur")
    {
        btnBoeking.IsHitTestVisible = true;
        btnBoeking.Opacity = 1;
    }
    else
    {
        btnBoeking.IsHitTestVisible = false;
        btnBoeking.Opacity = 0.5;
    }
}

这给了我一个错误。

Index was out of range. Must be non-negative and less than the size of the collection.

现在,当我调用代码但单击按钮时,它会按照它应该的方式工作。

private void tester_Click(object sender, RoutedEventArgs e)
{
    DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];
    test.Content = row.soort2;
    if (row.soort2 == "Factuur")
    {
        btnBoeking.IsHitTestVisible = true;
        btnBoeking.Opacity = 1;
    }
    else
    {
        btnBoeking.IsHitTestVisible = false;
        btnBoeking.Opacity = 0.5;
    }
}

为什么是这样?

4

3 回答 3

2

Why dont you use DataGrid SelectedIndexChanged event?

Wyy use GotFocus that doesnt tell you if user even made a selection to start with,

DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];

Called from gotfocus will fail as you have nothing selected besides having no error check in place to check if selection,

If you use Selection changed events you know the user has made selection changes there are a number of events for selection

于 2013-04-24T15:38:54.893 回答
0

因为 dtgVerkoopsdocumenten.SelectedItems 是空的并且GotFocus事件在事件之前引发,SelectedItemChanged所以我们不确定是否dtgVerkoopsdocumenten.SelectedItems有任何项目。你可以dtgVerkoopsdocumenten.SelectedItems在做任何事情之前检查。

    if (dtgVerkoopsdocumenten.SelectedItems != null && 
        dtgVerkoopsdocumenten.SelectedItems.Count > 0)
    { 
      DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];
      ...
    }
于 2013-04-24T14:13:21.870 回答
0

在按索引访问所选项目之前,您需要检查所选项目计数是否大于零条件。

于 2013-04-24T14:13:31.363 回答