【问题标题】:Force DataGrid column validation (WPF)强制 DataGrid 列验证 (WPF)
【发布时间】:2011-05-05 05:07:57
【问题描述】:
我想知道如何以编程方式对 DataGridColumn 进行验证。这与调用 BindingExpression 的 UpdateSource 方法几乎相同,但我无法获取列的 BindingExpression。
谢谢。
PS:在 ValidationRule 上设置 ValidatesOnTargetUpdated 属性不是我想要的:)
【问题讨论】:
标签:
c#
.net
wpf
data-binding
datagrid
【解决方案2】:
@user424096,
我无法访问我的 Visual Studio 环境,但以下伪代码可能会引导您以您想要的方式...
-
创建一个名为 NotifySourceUpdates 的附加布尔属性并附加到 DataGridCell...我已将它附加到数据网格级别,以便它适用于所有数据网格单元...您也可以将其附加到列级别...
<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) //// Please double check this signature
{
var uiElement = e.TargetObject as UIElement;
if (uiElement != null)
{
///... your code to validated uiElement.
}
}
-
这里你必须知道控件所代表的值是有效的还是无效的。
(uiElement.MyValue == null) //// Invalid!!
-
如果您希望控件的绑定无效,只需通过以下步骤使用 MarkInvalid 调用...
ValidationError validationError =
new ValidationError(myValidationRule,
uiElement.GetBindingExpression(UIElement.MyValueDependecyProperty));
validationError.ErrorContent = "Value is empty!";
Validation.MarkInvalid(uiElement.GetBindingExpression(UIElement.MyValueDependencyProperty), validationError);
让我知道这是否有效...