0

I am trying to convert this xaml textbox with validation into C# so that it can be dynamically created and populated from code. I am getting stuck creating the validation bindings. Can anyone provide any hints?

<TextBox Height="20" Width="200" >
      <Binding RelativeSource="{x:Static RelativeSource.Self}" Path="Text" >
           <Binding.ValidationRules>
                <runtime:StandardTextBoxValidationRule/>
           </Binding.ValidationRules>
       </Binding>
</TextBox>
2
  • Are you just dynamically creating the textbox from within the WPF page? Commented Sep 4, 2009 at 17:53
  • No it is being created in a control generating class that is with in the same assembly as the WPF page. Commented Sep 4, 2009 at 17:57

1 Answer 1

1

You can do it like so:

TextBox textBox = // Get or create the text box

var binding = new Binding();
binding.Source = RelativeSource.Self;
binding.Path = new PropertyPath("Text");
binding.ValidationRules.Add(new StandardTextBoxValidationRule());
textBox.SetBinding(TextBox.TextProperty, binding);
Sign up to request clarification or add additional context in comments.

3 Comments

I had to add the following to get it working binding.Path = new PropertyPath("Text"); Thanks again.
Glad it worked. I added that to my answer, as well, in case other poeple find this.
You can also use new Binding("Text")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.