![](/img/trans.png)
[英]Show Validation Error Template on Controls within a UserControl in WPF
[英]Show Validation Error in UserControl
我不確定為什么驗證狀態不會反映在我的用戶控件中。 我拋出異常,但由於某種原因,控件沒有顯示驗證狀態...當我在我的MainPage上使用標准Textbox
(現在在我的示例中注釋掉)時,它顯示錯誤狀態,不知道為什么它不包裹時。
我已經減少了這一點,所以基本上它是一個包裝TextBox
的用戶TextBox
。 我錯過了什么?
MyUserControl XAML:
<UserControl x:Class="ValidationWithUserControl.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="TextBox"/>
</Grid>
</UserControl>
MyUserControl代碼背后:
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MyUserControl_Loaded);
this.TextBox.Unloaded += new RoutedEventHandler(TextBox_Unloaded);
}
public string Value
{
get { return (string)base.GetValue(ValueProperty); }
set { base.SetValue(ValueProperty, value); }
}
public static DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value",
typeof(string),
typeof(MyUserControl),
new PropertyMetadata(null));
private void MyUserControl_Loaded(object sender, RoutedEventArgs e)
{
this.TextBox.SetBinding(TextBox.TextProperty, new Binding()
{
Source = this,
Path = new PropertyPath("Value"),
Mode = BindingMode.TwoWay,
ValidatesOnExceptions = true,
NotifyOnValidationError= true
});
}
private void TextBox_Unloaded(object sender, RoutedEventArgs e)
{
this.TextBox.ClearValue(TextBox.TextProperty);
}
}
我的主頁XAML:
<Grid x:Name="LayoutRoot" Background="LightBlue">
<StackPanel>
<uc:MyUserControl x:Name="UC" Value="{Binding Path=Value, Mode=TwoWay}" Height="20" Width="100" />
<!--TextBox x:Name="MS" Text="{Binding Path=Value, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" Height="20" Width="100" /-->
</StackPanel>
</Grid>
我的MainPage代碼背后:
public partial class MainPage : UserControl
{
private Model model;
//private Model model2;
public MainPage()
{
InitializeComponent();
this.model = new Model("UC");
//this.model2 = new Model("MS");
this.UC.DataContext = this.model;
//this.MS.DataContext = this.model2;
}
}
我的型號:
public class Model
{
public Model(string answer)
{
this.answer = answer;
}
private string answer;
public string Value
{
get
{
return this.answer;
}
set
{
if (!String.IsNullOrEmpty(value))
this.answer = value;
else
throw new Exception("Error");
}
}
}
好吧,我終於想出了如何處理這個問題。
您需要做的是從原始綁定復制驗證並將其發送到Textbox綁定。
要實現這一點,您需要做的第一件事是在用戶控件中實現INotifyDataErrorInfo接口。 然后,您必須驗證用戶控件以獲取GetErrors函數的確切驗證文本(可以使用Validation.GetErrors完成此操作)。
這是一個基本的實現,它在VB中,但我相信你明白了。
Public Event ErrorsChanged(ByVal sender As Object, ByVal e As System.ComponentModel.DataErrorsChangedEventArgs) Implements System.ComponentModel.INotifyDataErrorInfo.ErrorsChanged
Public Function GetErrors(ByVal propertyName As String) As System.Collections.IEnumerable Implements System.ComponentModel.INotifyDataErrorInfo.GetErrors
Dim returnValue As System.Collections.IEnumerable = Nothing
Dim errorMessage As String = Nothing
If propertyName = "Value" Then
If Validation.GetErrors(Me).Count = 0 Then
errorMessage = ""
Else
errorMessage = Validation.GetErrors(Me).First.ErrorContent.ToString
End If
If String.IsNullOrEmpty(errorMessage) Then
returnValue = Nothing
Else
returnValue = New List(Of String)() From {errorMessage}
End If
End If
Return returnValue
End Function
Public ReadOnly Property HasErrors As Boolean Implements System.ComponentModel.INotifyDataErrorInfo.HasErrors
Get
Return Validation.GetErrors(Me).Any()
End Get
End Property
接下來要做的就是通知你控制它變得無效。 您必須在2個地方執行此操作。
第一個將在BindingValidationError事件上 。 第二個將在Value PropertyChangedCallback函數中 (必須在注冊DependencyProperty時指定)
Public Shared ValueProperty As DependencyProperty = DependencyProperty.Register("Value", GetType(String), GetType(XDateTimePicker), New PropertyMetadata(Nothing, AddressOf ValuePropertyChangedCallback))
Public Shared Sub ValuePropertyChangedCallback(ByVal dependencyObject As DependencyObject, ByVal dependencyPropertyChangedEventArgs As DependencyPropertyChangedEventArgs)
DirectCast(dependencyObject, MyUserControl).NotifyErrorsChanged("Value")
End Sub
Private Sub MyUserControl_BindingValidationError(ByVal sender As Object, ByVal e As System.Windows.Controls.ValidationErrorEventArgs) Handles Me.BindingValidationError
Me.NotifyErrorsChanged("Value")
End Sub
Public Sub NotifyErrorsChanged(ByVal propertyName As String)
RaiseEvent ErrorsChanged(Me, New System.ComponentModel.DataErrorsChangedEventArgs(propertyName))
End Sub
大部分工作現在已完成,但您仍需要對綁定進行一些調整。
創建TextBox綁定時,需要將NotifyOnValidationError設置為False以避免原始綁定和Textbox綁定之間的通知循環。 需要將ValidatesOnExceptions , ValidatesOnDataErrors和ValidatesOnNotifyDataErrors設置為True。
Dim binding As New System.Windows.Data.Binding
binding.Source = Me
binding.Path = New System.Windows.PropertyPath("Value")
binding.Mode = Data.BindingMode.TwoWay
binding.NotifyOnValidationError = False
binding.ValidatesOnExceptions = True
binding.ValidatesOnDataErrors = True
binding.ValidatesOnNotifyDataErrors = True
Me.TextBox1.SetBinding(TextBox.TextProperty, binding)
最后,您需要在XAML中將NotifyOnValidationError和ValidatesOnNotifyDataErrors屬性設置為True。
<uc:MyUserControl x:Name="UC" Value="{Binding Path=Value, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnNotifyDataErrors=True}" Height="20" Width="100" />
您應該能夠將依賴項屬性綁定直接回顯到usercontrol文本框。 這將以與父視圖中的綁定相同的方式獲取驗證錯誤。 在您的MyUserControl_Loaded函數中:
var valueBinding = BindingOperations.GetBindingBase(this, ValueProperty);
if (valueBinding != null) TextBox.SetBinding(TextBox.TextProperty, valueBinding);
此行為是由添加的綁定級別引起的。 綁定不支持轉發驗證錯誤。
幕后發生的事情:
要解決此問題,您可以將文本框直接綁定到模型,如下所示:
this.TextBox.SetBinding(TextBox.TextProperty, new Binding()
{
Source = this.DataContext, // bind to the originating source
Path = new PropertyPath("Value"),
Mode = BindingMode.TwoWay,
ValidatesOnExceptions = true,
NotifyOnValidationError= true
});
從6個月過去了,我想知道你是否以及如何克服這個問題。
如果有人來尋找一個好的(閱讀:“不是用VBA編寫並完成”)這個問題的解決方案,我寫了一個基類 (雖然我只用無形控件測試它,不知道它是否適用於UserControl
s)基於@The_Black_Smurf在C#中的回答:
namespace MyApplication.Controls
{
using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
public abstract class ControlBaseWithValidation : Control, INotifyDataErrorInfo
{
public ControlBaseWithValidation()
{
// remove the red border that wraps the whole control by default
Validation.SetErrorTemplate(this, null);
}
public delegate void ErrorsChangedEventHandler(object sender, DataErrorsChangedEventArgs e);
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public bool HasErrors
{
get
{
var validationErrors = Validation.GetErrors(this);
return validationErrors.Any();
}
}
public IEnumerable GetErrors(string propertyName)
{
var validationErrors = Validation.GetErrors(this);
var specificValidationErrors =
validationErrors.Where(
error => ((BindingExpression)error.BindingInError).TargetProperty.Name == propertyName).ToList();
var specificValidationErrorMessages = specificValidationErrors.Select(valError => valError.ErrorContent);
return specificValidationErrorMessages;
}
public void NotifyErrorsChanged(string propertyName)
{
if (ErrorsChanged != null)
{
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}
protected static void ValidatePropertyWhenChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
((ControlBaseWithValidation)dependencyObject).NotifyErrorsChanged(dependencyPropertyChangedEventArgs.Property.Name);
}
}
}
使用ControlBaseWithValidation
類作為無外觀控件的基類而不是Control
類,並在要ValidatePropertyWhenChangedCallback
任何依賴項屬性上添加ValidatePropertyWhenChangedCallback
回調作為PropertyChangedCallback
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.