如何获得验证代码以在没有绑定的项目上执行?

| 问题: 我正在创建用于处理数据转换的用户控件(通过转换器/验证规则)。这可以按预期100%的方式运行,但是仅在控件绑定到某物时才触发验证,但情况并非总是如此。 即使控件未绑定,有没有办法强制验证?或有没有一种方法可以建立一个基本的虚拟绑定。 (该解决方案需要用代码完成,以便最终结果是拖放用户控件,而程序员无需进行xaml定制。 在此先感谢您的任何建议。 编辑:确实有问题的代码是这样的:
Binding TextBinding = BindingOperations.GetBinding(this, TextBox.TextProperty);
TextBinding.ValidationRules.Add(MyValidationRule);
这就是我分配验证规则的方式,但是只有TextBinding不为null时,它将起作用。因此,我要么需要为我的TextBox设置虚拟绑定,要么需要添加验证规则的另一种方法。     
已邀请:
        在我看来,您想要做的就是在用户控件上定义一个依赖属性,该属性将用户控件中的XAML绑定到该属性。此绑定将合并您的验证规则。然后,用户控件的使用者将用户控件上的属性绑定到他们想要的任何内容。 如果没有确切的用例,很难做到比这更具体,但是请考虑以下几点: CoolUserControl.xaml.cs:
public class CoolUserControl : UserControl
{
    public static readonly DependencyProperty CoolProperty = ...;

    public string Cool
    {
        // get / set
    }
}
CoolUserControl.xaml:
<UserControl x:Name=\"root\" ...>
    <TextBox>
        <TextBox.Text>
            <Binding Path=\"Cool\" ElementName=\"root\">
                <Binding.ValidationRules>
                    <!-- your rule here -->
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
</UserControl>
SomeConsumer.xaml:
<local:CoolUserControl Cool=\"{Binding SomePropertyOnMyViewModel}\"/>
    

要回复问题请先登录注册