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 f开发者_开发百科or 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}"/>
精彩评论