WPF 検証システムは、オブジェクトの初期検証を実行します (つまり、データバインドされたアイテムが変更されるとすべてのフィールドが検証され、結果が UI に表示されます)。しかし、コントロールを動的に追加すると、このようには機能しません。このような場合、最初の検証が行われますが、結果は UI に表示されません。データバインドされたオブジェクトのいくつかのプロパティが変更された後でのみ、すべてが正しく機能し始めます。これが粗いサンプルです。
MyObject クラスがあるとします
public class MyObject : INotifyPropertyChanged, IDataErrorInfo
{
public string Name { /*get, set implementation */}
// IDataErrorInfo
public string this[string columnName]
{
get
{
if (String.IsNullOrEmpty(Name)) return "Name can't be empty!";
return String.Empty;
}
}
/* etc. */
}
また、MyObject オブジェクトの編集を可能にする MyUserControl などのユーザー コントロールもあります。どういうわけか次のようになります。
<UserControl x:Class="Test.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name: "/>
<TextBox Text="{Binding Name, ValidatesOnDataErrors=True}" Width="200"/>
</StackPanel>
</UserControl>
現在、このコントロールが xaml のメイン ウィンドウ (またはコンストラクターまたはウィンドウ ロード イベントのコード ビハインド) に追加されている場合、MyCustomControl.DataContext が MyObject クラスの新しいインスタンスに設定されている場合よりも、Name フィールドがすぐに検証され、エラー通知が行われます。検証エラー テンプレートを使用して表示されます。ただし、MyCustomControl が動的に追加されると (たとえば、ボタンがクリックされた後)、最初の検証が行われますが、UI に結果が表示されません (赤い境界線がないなど)。
アプリケーション ウィンドウがドックパネル (dockPanel) とボタンで構成されているとします。
public Window1()
{
InitializeComponent();
button.Click +=new RoutedEventHandler(OnButtonClick);
/*
// in this case validation works correctly,
// when window is shown Name textbox already got a red border etc.
var muc = new MyUserControl();
dockPanel.Children.Add(muc);
muc.DataContext = new MyObject();
*/
}
private void OnButtonClick(object sender, RoutedEventArgs e)
{
// in this case validatation works, but no results are shown on the ui
// only after Name property is changed (then removed again) red border appears
var muc = new MyUserControl();
dockPanel.Children.Add(muc);
muc.DataContext = new MyObject();
}
なんで?