簡體   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