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

时间:2014-08-25 11:39:11

标签: c# wpf xaml mvvm messagebox

我已经使用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);
        }));
    }
}    

1 个答案:

答案 0 :(得分:1)

在您的类中实现IDataErrorInfo添加索引器MessageBox。为了在离开TextBox集后只显示一次

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

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