从XAML强制验证绑定控件?

时间:2009-08-21 20:11:41

标签: wpf validation xaml

已发布very similar question。实际上,该帖子中答案的结果正是我所追求的,但我没有代码隐藏来放置代码。我们所有的逻辑都封装在ViewModel中。由于ViewModel不应该直接引用特定的可视元素,因此该代码也不存在。有没有办法以某种方式在XAML中执行相同的操作,或者我最终遇到了被迫创建代码隐藏文件的原因?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用附加属性做一些事情..这有点精心,但它与其他答案一样,所以我认为它应该有效:

public class DependencyPropertyCollection : List<DependencyProperty>
{ }

public static class ValidationUtil
{
    public static readonly DependencyProperty ForceValidationProperty =
        DependencyProperty.RegisterAttached("ForceValidation", typeof(DependencyPropertyCollection), typeof(ValidationUtil), new PropertyMetadata(OnForceValidationChanged));
    private static void OnForceValidationChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)sender;
        element.Loaded += OnElementLoaded;
    }

    private static void OnElementLoaded(object sender, RoutedEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)sender;
        element.Loaded -= OnElementLoaded;
        foreach (DependencyProperty property in GetForceValidation(element))
            element.GetBindingExpression(property).UpdateSource();
    }

    public static DependencyPropertyCollection GetForceValidation(DependencyObject obj)
    {
        return (DependencyPropertyCollection)obj.GetValue(ForceValidationProperty);
    }
    public static void SetForceValidation(DependencyObject obj, DependencyPropertyCollection value)
    {
        obj.SetValue(ForceValidationProperty, value);
    }
}

你这样使用它:

<TextBlock Text="{Binding Text}">
    <local:ValidationUtil.ForceValidation>
        <local:DependencyPropertyCollection>
            <x:StaticExtension Member="TextBlock.TextProperty"/>
        </local:DependencyPropertyCollection>
    </local:ValidationUtil.ForceValidation>
</TextBlock>

在集合中,您可以指定每个DependencyProperty,它具有您要验证的绑定。