私は、Employeeオブジェクトをリストにバインドされwchichデータグリッドを持つ単純なWPFアプリケーション作られた:あなたが見ることができるようにWPFデータグリッドの新しい行の検証
public class Employee
{
private string _name;
public int Id { get; set; }
public string Name
{
get { return _name; }
set
{
if (String.IsNullOrEmpty(value))
throw new ApplicationException("Name cannot be empty. Please specify the name.");
_name = value;
}
}
を、私は設定Nameプロパティなしで従業員を作成しないようにしたいです。
public class StringValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string str = value as string;
if (String.IsNullOrEmpty(str))
return new ValidationResult(false, "This field cannot be empty");
else
return new ValidationResult(true, null);
}
}
名前フィールドのためのXAMLは以下の通りです: だから、私は、検証ルールを作っ
<DataGridTextColumn Header="Name"
ElementStyle="{StaticResource datagridElStyle}" >
<DataGridTextColumn.Binding>
<Binding Path="Name" Mode="TwoWay" NotifyOnValidationError="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<emp:StringValidationRule/>
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
私はDataGrid内の既存の従業員行の名前を編集して空にし、それを設定しよう文字列の場合、datagridは間違ったフィールドをマークし、行を保存することはできません。これは正しい動作です。
しかし、新しい行を作成してキーボードでEnterキーを押すと、_nameがNULLに設定されたこの新しい行が作成され、検証は機能しません。私はDataGridが新しい行オブジェクトのデフォルトのコンストラクタを呼び出し、_nameフィールドをNULLに設定するためだと思います。
新しい行の正しい検証方法は何ですか?
THanks、私はそれを調べ、解決策があればここに投稿します。しかし、編集の検証はうまく動作し、新しい行を検証する簡単な方法があると思っていました。これはかなり一般的な作業です。 – MyUserName
はい、EmployeeクラスのIDataErrorの実装が助けになりました。私はここで良い例を見つけました:http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx#errorinfo – MyUserName
@MyUserName:喜んで助けてください。 :) –