我想知道如何在DataGridColumn上编程触发验证。这与调用BindingExpression的UpdateSource方法几乎相同,但我无法管理列的BindingExpression。
谢谢。
PS:设置ValidationRule的ValidatesOnTargetUpdated属性不是我要找的 :)
谢谢。
PS:设置ValidationRule的ValidatesOnTargetUpdated属性不是我要找的 :)
@user424096,
很抱歉,我无法访问我的Visual Studio环境,但以下伪代码可能会指导您实现所需的方法...
创建一个名为NotifySourceUpdates的附加布尔属性,并将其附加到DataGridCell...我已经将其附加到了datagrid级别,以便它适用于所有数据网格单元格...你也可以将其附加到列级别...
<DataGrid ItemsSource="{Binding}">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" >
<Setter Property="ns:MyAttachedBehavior.NotifySourceUpdates" Value="True"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
这个附加行为将处理单元格级别的附加事件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);
}
}
在此事件处理程序中,事件参数的类型为DataTransferEventArgs,它会给你TargetObject。这将是需要验证的控件。
private static void OnSourceUpdatedHandler(object obj, DataTransferEventArgs e) //// 请仔细检查此签名
{
var uiElement = e.TargetObject as UIElement;
if (uiElement != null)
{
///... your code to validated uiElement.
}
}
在这里,您必须知道由控件表示的值是有效还是无效。
(uiElement.MyValue == null) //// 无效!!
如果您希望控件的绑定无效,请使用以下步骤调用MarkInvalid...
ValidationError validationError =
new ValidationError(myValidationRule,
uiElement.GetBindingExpression(UIElement.MyValueDependecyProperty));
validationError.ErrorContent = "Value is empty!";
Validation.MarkInvalid(uiElement.GetBindingExpression(UIElement.MyValueDependencyProperty), validationError);
请告诉我这是否有效...
http://www.codeproject.com/KB/dotnet/ValidationDotnetFramework.aspx