切换选项卡时,Wpf强制IDataErrorInfo验证无效

时间:2016-09-14 21:21:56

标签: c# wpf validation idataerrorinfo

answer之后,我能够在WPF 4.0中触发验证错误。但是,切换标签时它不起作用。奇

这里是sample。转到选项卡2,单击按钮,切换到选项卡1,再次切换到选项卡2,然后单击按钮。第二次,没有显示错误装饰。

视图模型

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>

代码

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");
    }
  }
}

任何见解?

0 个答案:

没有答案