我使用xaml创建了以下视图
<StackPanel Style="{StaticResource Col}"> <DockPanel> <GrID DockPanel.Dock="top"> <GrID.ColumnDeFinitions > <ColumnDeFinition WIDth="*" ></ColumnDeFinition> <ColumnDeFinition WIDth="*"></ColumnDeFinition> </GrID.ColumnDeFinitions> <StackPanel GrID.Column="0" Style="{StaticResource Col}"> <Label Content="name" Style="{StaticResource Formlabel}" /> <border Style="{StaticResource Forminputborder}"> <TextBox x:name="name" Style="{StaticResource FormControl}" Text="{Binding name,ValIDatesOnDataErrors=True,NotifyOnValIDationError=True,UpdateSourceTrigger=PropertyChanged}" /> </border> </StackPanel> <StackPanel GrID.Column="1" Style="{StaticResource Col}"> <Label Content="Phone Number" Style="{StaticResource Formlabel}" /> <border Style="{StaticResource Forminputborder}"> <TextBox x:name="Phone" Style="{StaticResource FormControl}" Text="{Binding Phone,UpdateSourceTrigger=PropertyChanged}" /> </border> </StackPanel> </GrID> <StackPanel OrIEntation="Horizontal" HorizontalAlignment="Center"> <button Style="{StaticResource Primarybutton}" Command="{Binding Create}">Create</button> <button>reset</button> </StackPanel> </DockPanel></StackPanel>
然后我创建了以下viewmodel
public class vendorviewmodel : viewmodel{ protected Readonly IUnitOfWork UnitOfWork; private string _name { get; set; } private string _Phone { get; set; } public vendorviewmodel() : this(new UnitOfWork()) { } public vendorviewmodel(IUnitOfWork unitOfWork) { UnitOfWork = unitOfWork; } [required(ErrorMessage = "The name is required")] [MinLength(5,ErrorMessage = "name must be more than or equal to 5 letters")] [MaxLength(50,ErrorMessage = "name must be less than or equal to 50 letters")] public string name { get { return _name; } set { _name = value; NotifyPropertyChanged(); } } public string Phone { get { return _Phone; } set { _Phone = value; NotifyPropertyChanged(); } } /// <summary> /// Gets the collection of customer loaded from the data store. /// </summary> public ICollection<vendor> vendors { get; private set; } protected voID Addvendor() { var vendor = new vendor(name,Phone); UnitOfWork.vendors.Add(vendor); } public ICommand Create { get { return new ActionCommand(p => Addvendor(),p => IsValIDRequest()); } } public bool IsValIDRequest() { // There got to be a better way to check if everything passed or Now... return IsValID("name") && IsValID("Phone"); }}
这是我的viewmodel基类的样子
public abstract class viewmodel : ObservableObject,IDataErrorInfo{ /// <summary> /// Gets the valIDation error for a property whose name matches the specifIEd <see cref="columnname"/>. /// </summary> /// <param name="columnname">The name of the property to valIDate.</param> /// <returns>Returns a valIDation error if there is one,otherwise returns null.</returns> public string this[string columnname] { get { return OnValIDate(columnname); } } /// <summary> /// ValIDates a property whose name matches the specifIEd <see cref="propertyname"/>. /// </summary> /// <param name="propertyname">The name of the property to valIDate.</param> /// <returns>Returns a valIDation error,if any,otherwise returns null.</returns> protected virtual string OnValIDate(string propertyname) { var context = new ValIDationContext(this) { Membername = propertyname }; var results = new Collection<ValIDationResult>(); bool isValID = ValIDator.TryValIDateObject(this,context,results,true); if (!isValID) { ValIDationResult result = results.SingleOrDefault(p => p.Membernames.Any(membername => membername == propertyname)); if (result != null) return result.ErrorMessage; } return null; } protected virtual bool IsValID(string propertyname) { return OnValIDate(propertyname) == null; } /// <summary> /// Not supported. /// </summary> [Obsolete] public string Error { get { throw new NotSupportedException(); } }}
这是我的ObservableObject类
public class ObservableObject : INotifyPropertyChanged{ /// <summary> /// Raised when the value of a property has changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises <see cref="PropertyChanged"/> for the property whose name matches <see cref="propertyname"/>. /// </summary> /// <param name="propertyname">Optional. The name of the property whose value has changed.</param> protected voID NotifyPropertyChanged([CallerMembername] string propertyname = "") { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this,new PropertyChangedEventArgs(propertyname)); } }}
我的目标是在不正确的字段周围显示一个红色边框,然后在它下面显示错误消息,告诉使用出了什么问题.
如何正确显示错误?另外,如何在首次加载视图时不显示任何错误?
基于此blog,我需要编辑ValIDation.ErrorTemplate
所以我尝试将以下代码添加到App.xaml文件中
<!-- Style the error valIDation by showing the text message under the fIEld --> <Style targettype="TextBox"> <Setter Property="ValIDation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <StackPanel> <border borderThickness="1" borderBrush="DarkRed"> <StackPanel> <AdornedElementPlaceholder x:name="errorControl" /> </StackPanel> </border> <TextBlock Text="{Binding AdornedElement.tooltip,Elementname=errorControl}" Foreground="Red" /> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="ValIDation.HasError" Value="true"> <Setter Property="borderBrush" Value="Red" /> <Setter Property="borderThickness" Value="1" /> <Setter Property="tooltip" Value="{Binding relativeSource={relativeSource Self},Path=(ValIDation.Errors)[0].ErrorContent}" /> </Trigger> </Style.Triggers> </Style>
但是这没有显示错误消息,也是在第一次加载视图时我得到一个错误.最后,即使表单生效, *** 作按钮也会保持禁用状态.
更新
将Property =“ValIDation.ErrorTemplate”移动到FormControl组后,它工作了.但是,错误消息似乎是通过按钮而不是按下按钮.此外,文本似乎没有垂直包装,允许边框覆盖其他控件,如下面的屏幕显示所示.
解决方法 我会尽力回答你的所有问题:
如何正确显示错误?
不应用ErrorTemplate,因为TextBox上的FormControl样式优先于包含ValIDation.ErrorTemplate的样式.将ValIDation.ErrorTemplate代码移动到FormControl样式将解决此问题.
另外,如何在首次加载视图时不显示任何错误?
如果不立即应用,必要验证的用途是什么?只有在开始键入字段时才会执行MinLength和MaxLength验证.
但是,错误消息似乎是通过按钮而不是按下按钮.
正如Will指出的那样,这是因为错误消息显示在AdornerLayer上,它不会干扰控件所在的层.您有以下选择:
>使用AdornerLayer但在控件之间留出一些空间
>使用工具提示显示错误消息
>在TextBox的模板中使用额外的TextBlock,以显示错误消息.
这些选项描述为here
总结以上是内存溢出为你收集整理的c# – 如何在WPF应用程序中显示错误消息?全部内容,希望文章能够帮你解决c# – 如何在WPF应用程序中显示错误消息?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)