简体   繁体   中英

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.

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.

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. So I either need a dummy binding for my TextBox, or another way to add the validation rule.

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. 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 :

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}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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