简体   繁体   English

如何让我的验证代码在没有绑定的项目上执行?

[英]How can I get my validation code to execute on an item with no binding?

The Problem: I am creating user control that handles data conversions (via a converter/validation rule).问题:我正在创建处理数据转换的用户控件(通过转换器/验证规则)。 This works 100% as desired, but the validation only fires when the control is bound to something, which is not always the case.这可以按要求 100% 工作,但仅当控件绑定到某物时才会触发验证,但情况并非总是如此。

Is there a way to force validation even if the control is not bound?即使控件未绑定,有没有办法强制验证? OR is there a way to set up basically a dummy binding.或者有没有办法基本上设置一个虚拟绑定。 (The solution needs to be done in code so that the end result is a drag and drop user control with no xaml customization needed by the programmer. (解决方案需要在代码中完成,以便最终结果是拖放用户控件,程序员不需要 xaml 自定义。

Thanks in advance for any advice.提前感谢您的任何建议。

EDIT: Really the code in question is this:编辑:真的有问题的代码是这样的:

Binding TextBinding = BindingOperations.GetBinding(this, TextBox.TextProperty);
TextBinding.ValidationRules.Add(MyValidationRule);

This is how I am assigning my validation rule, but it will only work if the TextBinding is not null.这就是我分配验证规则的方式,但它仅在 TextBinding 不是 null 时才有效。 So I either need a dummy binding for my TextBox, or another way to add the validation rule.所以我要么需要为我的 TextBox 设置一个虚拟绑定,要么需要另一种方式来添加验证规则。

Sounds to me like what you want to be doing is defining a dependency property on your user control which the XAML in your user control binds to.在我看来,您想要做的是在您的用户控件上定义一个依赖属性,您的用户控件中的 XAML 绑定到该属性。 This binding would incorporate your validation rule.此绑定将包含您的验证规则。 Consumers of your user control would then bind the property on your user control to whatever they want.然后,您的用户控件的使用者会将您的用户控件上的属性绑定到他们想要的任何内容。

It's really hard to be more specific than that without your exact use case, but consider this:如果没有您的确切用例,真的很难比这更具体,但请考虑一下:

CoolUserControl.xaml.cs : CoolUserControl.xaml.cs

public class CoolUserControl : UserControl
{
    public static readonly DependencyProperty CoolProperty = ...;

    public string Cool
    {
        // get / set
    }
}

CoolUserControl.xaml : 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 : SomeConsumer.xaml

<local:CoolUserControl Cool="{Binding SomePropertyOnMyViewModel}"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM