WPF:在C#code排检测验证错误错误、WPF、code

2023-09-07 12:30:53 作者:苦笑流年记忆

我想实现一个pretty的简单的任务,但没有发现曾经帮助过我迄今为止解决方案在这里的SO或以其他方式:

I want to achieve a pretty simple task, but none of the solutions here on SO or otherwise found have helped me so far:

我有一个WPF 的DataGrid ,这势必类型化的数据集。当我点击我的窗口中的OK按钮,我想检测是否有目前任何行验证错误。我想显示一个消息框,告诉来解决这些错误的用户。

I have a WPF DataGrid, which is bound to a typed data set. When I click the OK button in my window, I want to detect whether there are currently any row validation errors. I want to show a message box and tell the user to resolve these errors.

我怎样才能做到这一点?

How can I achieve this?

修改 为了使我的问题多一点precise:

EDIT To make my question a bit more precise:

该类型化的DataSet,我结合是一个包含一个表一个简单的数据集。这些表是通过调用填充一个WCF服务,并有在表5文本列。一些这些列的有长度的限制(例如,一列可能只需要5个字符)。

The typed dataset I'm binding to is a simple data set that contains a table. The tables is filled from a call to a WCF service and there are 5 text columns in the table. Some of these columns have length constraints (for example, one column may only take 5 characters).

的ItemsSource 我的的GridView 在code设置如下:

The ItemsSource of my GridView is set in code as follows:

dgvData.ItemsSource = m_dataModel.TableName;

如果我输入一些文本列,一切都很好。进入超过5个字符到所述柱,将显示红色行误差标记旁边的行。我没有做任何定制验证(还)。

If I enter some text into the columns, all is well. Entering more than 5 characters into said column, the red row error marker is displayed next to the row. I am not doing any custom validation (yet).

我可以看到红色感叹号,但我无法确定在code无论是可见或不可见。我试着:

I can see the red exclamation mark, but I'm not able to determine in code whether it is visible or not. I've tried to:

使用数据集的 HasErrors 属性(返回 Validation.GetHasErrors(dgvData)返回和 的soluction HB在他的评论中提到,但没有奏效 Use the data set's HasErrors property (returns false) Validation.GetHasErrors(dgvData) returns false as well the soluction H.B.'s mentioned in his comment, but it didn't work

我在这里丢失? - 必须有这样做的一个简单的方法

I'm at a loss here - there must be a simple way of doing this?

推荐答案

好了,我的工作了。下面我想要做什么:

OK, I've worked it out. The following does what I want:

public static DataGridRow GetRow(DataGrid grid, int index)
{
    DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // May be virtualized, bring into view and try again.
        grid.UpdateLayout();
        grid.ScrollIntoView(grid.Items[index]);
        row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

在$ C $下我的确定按钮,我做的:

In the code for my "OK" button I do:

for (int i = 0; i < dgvData.Items.Count; i++)
{
    DataGridRow row = GetRow(dgvData, i);
    if (row != null && Validation.GetHasError(row))
    {
        hasDataGridErrors = true;
        break;
    }
}