我是WPF的新手,目前正在學習驗證。 在我簡單的例子,我有這樣的模型類:ValidatesOnExceptions與ValidatesOnDataErrors衝突
class Book
{
public int Id
{
get { return id; }
set
{
if (id == value) return;
id = value;
OnPropertyChanged(nameof(Id));
}
}
public string Title
{
get { return title; }
set
{
if (title == value) return;
title = value;
OnPropertyChanged(nameof(Title));
OnPropertyChanged(nameof(PagesCount));
}
}
public int PagesCount
{
get { return pagesCount; }
set
{
if (pagesCount == value) return;
pagesCount = value;
OnPropertyChanged(nameof(Title));
OnPropertyChanged(nameof(PagesCount));
}
}
public string Color
{
get { return color; }
set
{
if (color == value) return;
color = value;
OnPropertyChanged(nameof(Color));
}
}
}
我實現IDataErorInfo
和INotifyDataErorInfo
。 的我的驗證規則之一(編寫測試的緣故),是用戶無法進入冠軍都SS
和33
在PagesCount,所以我說這在INotifyDataErrorInfo
的索引:
case nameof(Title):
if (Title == "N")
{
AddError(nameof(Title), "Annoying");
hasError = true;
}
if (Title == "SS" && PagesCount == 33)
{
AddError(nameof(Title), "SS and 33 not compatible");
hasError = true;
}
if (!hasError)
ClearErrors(nameof(Title));
break;
case nameof(PagesCount):
if (Title == "SS" && PagesCount == 33)
{
AddError(nameof(Title), "SS and 33 not compatible");
hasError = true;
}
if (!hasError)
ClearErrors(nameof(Title));
break;
當我進入這些值(SS爲標題和33 PagesCount)的紅色邊框出現,這個模板中的錯誤信息顯示:
<ListBox Grid.Row="8" Grid.ColumnSpan="2" ItemsSource="{Binding ElementName=mGrd, Path=(Validation.Errors)}">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding Path=ErrorContent}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
但是當我輸入的值無效的PagesCount(無效int
)像33E噸他錯誤消息不會從列表框中消失,並且邊框仍然裝飾兩個文本框。 我不知道爲什麼它不能清除錯誤模板中的錯誤消息,只是保持紅色邊框,所以有辦法做到這一點,也可以顯示消息的這種例外(輸入33eint
場)
爲什麼輸入*無效*值時邊框會消失? – mm8