如何在wpf文本块验证错误上显示消息框

本文关键字:错误 显示 消息 验证 wpf 文本 | 更新日期: 2023-09-27 18:19:16

我已经使用IDataErrorInfo实现了对Datagrid单元格模板的验证,并且能够显示工具提示错误消息。如何显示带有错误信息的消息框而不是工具提示?

  <DataGridTemplateColumn Header="Code" MinWidth="150">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Code, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Style="{StaticResource TextBlockStyle}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Code, UpdateSourceTrigger=LostFocus}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
  </DataGridTemplateColumn>
  <Style x:Key="TextBlockStyle" TargetType="{x:Type TextBlock}">
           <Style.Triggers>
              <Trigger Property="Validation.HasError" Value="true">
                 <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
              </Trigger>
           </Style.Triggers>
  </Style>

IDataErrorInfo实现类

public class CurrencyExchangeRate : ObservableObject, IDataErrorInfo
{
    private string _code;
    public string Code
    {
        get { return _code; }
        set
        {
             if (_code != value)
            {
                _code = value;
                if (!string.IsNullOrEmpty(_code))
                {
                    RaisePropertyChangedEvent("Code");
                }
            }
        }
    }  
    public string this[string columnName]
    {
        get
        {
            string error = string.Empty;
            switch (columnName)
            {
                case "Code":
                    if (string.IsNullOrEmpty(_code))
                    {
                        error = "Code cannot be empty";
                        ShowMessage(error);
                    }
                    break;
            }
            return error;
        }
    }  
    public static void ShowMessage(string error)
    {
        System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
        {
            System.Windows.Forms.MessageBox.Show(error);
        }));
    }
}    

如何在wpf文本块验证错误上显示消息框

在你的类实现IDataErrorInfo添加在indexer MessageBox。为了在离开TextBox set后只显示一次

 <TextBox Text="{Binding Code, UpdateSourceTrigger=LostFocus}"/>

它将在失去焦点后提供检查验证