WPF Validation & IDataErrorInfo

Note - the classes that I have are EntityObject classes!

I have the following class:

 public class Foo { public Bar Bar { get; set; } } public class Bar : IDataErrorInfo { public string Name { get; set; } #region IDataErrorInfo Members string IDataErrorInfo.Error { get { return null; } } string IDataErrorInfo.this[string columnName] { get { if (columnName == "Name") { return "Hello error!"; } Console.WriteLine("Validate: " + columnName); return null; } } #endregion } 

XAML is as follows:

 <StackPanel Orientation="Horizontal" DataContext="{Binding Foo.Bar}"> <TextBox Text="{Binding Path=Name, ValidatesOnDataErrors=true}"/> </StackPanel> 

I set a breakpoint and Console.Writeline to check there - I have no breaks. Verification is not performed. Can someone just push me to the place where my mistake lies?

+4
source share
6 answers

This might be a dumb answer, but by default, binding causes a setter when LostFocus happens. Try this if you haven’t.

If you want the error code to run every time you press a key, use UpdateSourceTrigger=PropertyChanged inside the binding.

+2
source

You forgot to implement INotifyPropertyChanged in the "Bar" class, then only the binding system will call the setter.

Thus, your "Name" property should most likely be.

 public string Name { get{ return _name; } set { _name = value; RaisePropertyChanged("Name"); // Or the call might OnPropertyChanged("Name"); } } 
+1
source

I am not familiar with the EntityObject class and cannot find it in the .NET Framework documentation or google quick search.

In any case, you need to use NotifyOnValidationError :

 <TextBox Text="{Binding Path=Name, ValidatesOnDataErrors=true, NotifyOnValidationError=true}"/> 
+1
source

Try setting = TwoWay mode to bind

+1
source

You must create a local window resource that contains a reference to the Bar class and use its key to set the StackPanel data context property. Also, be sure to import your namespace into a window or user control.

Your XAML code should look like this:

 <Window x:Class="Project.WindowName" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BarNamespace"> <Window.Resources> <local:Bar x:Key="bar" /> </Window.Resources> <StackPanel Orientation="Horizontal" DataContext="{StaticResource bar}"> <TextBox Text="{Binding Path=Name, ValidatesOnDataErrors=true}"/> </StackPanel> </Window> 
+1
source

You must make methods that implement IDataErrorInfo as public.

-1
source

Source: https://habr.com/ru/post/1304759/


All Articles