繁体   English   中英

强制DataGrid列验证(WPF)

[英]Force DataGrid column validation (WPF)

我想知道如何以编程方式在DataGridColumn上激活验证。 它和donde调用BindingExpression的UpdateSource方法几乎相同,但是我无法获得列的BindingExpression。

谢谢。

PS:在ValidationRule上设置ValidatesOnTargetUpdated属性不是我想要的:)

在.NET Framework 4中,名为System.ComponentModel.DataAnnotations的命名空间可用于公共CLR(WPF)和较轻的Silverlight CLR。 您可以将DataAnnotations命名空间用于各种目的。 其中一个是使用属性进行数据验证,另一个是字段,属性和方法的可视化描述,或自定义特定属性的数据类型。 这三个类别在.NET Framework中分类为验证属性,显示属性和数据建模属性。 本节使用验证属性来定义对象的验证规则

http://www.codeproject.com/KB/dotnet/ValidationDotnetFramework.aspx

@ user424096,

我无法访问我的视觉工作室环境,但遵循伪代码可能会指导您按照您想要的方式...

  1. 创建一个名为NotifySourceUpdates的附加布尔属性,并将其附加到DataGridCell ...我已将其附加到datagrid级别,以便它适用于所有数据网格单元...您也可以在列级别附加它...

      <DataGrid ItemsSource="{Binding}"> <DataGrid.CellStyle> <Style TargetType="DataGridCell" > <Setter Property="ns:MyAttachedBehavior.NotifySourceUpdates" Value="True"/> </Style> </DataGrid.CellStyle> </DataGrid> 
  2. 此附加行为将处理在单元级别称为Binding.SourceUpdated的附加事件。 因此,每当任何绑定作为任何子UI元素的正常或编辑模式的一部分更新其源时,它将触发并冒泡到单元级别。

      public static readonly DependencyProperty NotifySourceUpdatesProperty = DependencyProperty.RegisterAttached( "NotifySourceUpdates", typeof(bool), typeof(MyAttachedBehavior), new FrameworkPropertyMetadata(false, OnNotifySourceUpdates) ); public static void SetNotifySourceUpdates(UIElement element, bool value) { element.SetValue(NotifySourceUpdatesProperty, value); } public static Boolean GetNotifySourceUpdates(UIElement element) { return (bool)element.GetValue(NotifySourceUpdatesProperty); } private static void OnNotifySourceUpdates(DependencyObject d, DependencyPropertyEventArgs e) { if ((bool)e.NewValue) { ((DataGridCell)d).AddHandler(Binding.SourceUpdated, OnSourceUpdatedHandler); } } 
  3. 在此事件处理程序中,事件args的类型为DataTransferEventArgs,它为您提供TargetObject。 这将是您需要验证的控件。

     private static void OnSourceUpdatedHandler(object obj, DataTransferEventArgs e) //// Please double check this signature { var uiElement = e.TargetObject as UIElement; if (uiElement != null) { ///... your code to validated uiElement. } } 
  4. 在这里,您必须知道控件表示的值是有效还是无效。

     (uiElement.MyValue == null) //// Invalid!! 
  5. 如果您希望控件的绑定无效,只需使用这些步骤使用MarkInvalid调用...

     ValidationError validationError = new ValidationError(myValidationRule, uiElement.GetBindingExpression(UIElement.MyValueDependecyProperty)); validationError.ErrorContent = "Value is empty!"; Validation.MarkInvalid(uiElement.GetBindingExpression(UIElement.MyValueDependencyProperty), validationError); 

让我知道这个是否奏效...

您可以考虑实现System.ComponentModel.IDataErrorInfo来为这些输入提供验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM