WPF Learner
WPF Learner

Reputation: 17

Binding Error Validation In Code and not in XAML

I understand how to bind and handle Validation Errors when setting an event in XAML as shown below, what I now need to do is Add the same Error Handler but totally in code with no XAML as I add the controls at run time in code. I have searched but cannot find anything that point me in the right direction.

<Grid>
    <TextBox Validation.Error="TextBox_Error" />
</Grid>

Upvotes: 1

Views: 198

Answers (2)

Akhitha M D
Akhitha M D

Reputation: 164

You can also set Binding for a control and add ValidationRules for the binding

            TextBox txtBox = new TextBox();
            txtBox.DataContext = // Your data;

            Binding binding = new Binding();
            binding.Path = // Set path;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            binding.ValidatesOnDataErrors = true;
            binding.NotifyOnValidationError = true;
            binding.ValidationRules.Add(// Your ValidationRule class);
            txtBox.SetBinding(TextBox.TextProperty, binding);

Upvotes: 1

vasily.sib
vasily.sib

Reputation: 4002

If inderstand you right, here is what you looking for:

var element = yourRunTimeControl as DependencyObject;
System.Windows.Controls.Validation.AddErrorHandler(element, ErrorHandler)

private void ErrorHandler(object sender, System.Windows.Controls.ValidationErrorEventArgs e)
{
    ...
}

You can read more about Validation.Error attached event here.

Upvotes: 0

Related Questions