KithKann
KithKann

Reputation: 31

Converting XAML Textbox to C# with Validation

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>

Upvotes: 0

Views: 990

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564363

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);

Upvotes: 1

Related Questions