2

Following this answer I was able to trigger validation error in WPF 4.0. However, it doesn't work when switching tabs. Odd.

Here's the sample. Go to tab 2, click the button, switch to tab 1, switch to tab 2 again and click the button. This second time, no error adorner is shown.

ViewModel

class ViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private List<string> errors;
    public event PropertyChangedEventHandler PropertyChanged;

    public ViewModel()
    {
        errors = new List<string>();
    }

    private string text;
    public string Text
    {
        get { return text; }
        set
        {
            text = value;
            RaisePropertyChanged("Text");
        }
    }

    public void Validate()
    {
        errors.Clear();
        if (string.IsNullOrEmpty(Text))
            errors.Add("Required field");
    }

    public void RaisePropertyChanged(string p)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(p));
    }

    string IDataErrorInfo.Error
    {
        get { return errors.FirstOrDefault(); }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            if (columnName == "Text")
                return errors.FirstOrDefault();

            return null;
        }
    }
}

XAML

<Window x:Class="ErrorAdorner.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TabControl>
        <TabItem Header="First">
            <TextBlock Text="Nothing here"/>
        </TabItem>
        <TabItem Header="Second">
            <StackPanel>
                <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>
                <Button Content="Trigger" Click="Button_Click" Margin="0,30,0,0"/>
            </StackPanel>
        </TabItem>
    </TabControl>
</Grid>

Code behind

using System.Windows;

namespace ErrorAdorner
{
public partial class MainWindow : Window
{
    private ViewModel model;
    public MainWindow()
    {
        InitializeComponent();
        DataContext = model = new ViewModel();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        model.Validate();
        model.RaisePropertyChanged("Text");
    }
  }
}

Any insights?

Community
  • 1
  • 1
JobaDiniz
  • 862
  • 1
  • 14
  • 32

0 Answers0