18

I want to use the ValidationRules (and it's UI effects) on the textbox without actually binding anything to the textbox.

I want to use the textbox for some input that doesn't bound to anything but need to validate the input after focus is lost using the ValidationRules.

Can it be done?

<TextBox.Text>
   <Binding Path="" UpdateSourceTrigger="LostFocus">
     <Binding.ValidationRules>
        <local:IntegersOnlyValidator/>
     </Binding.ValidationRules>
   </Binding>
 </TextBox.Text>
H.B.
  • 166,899
  • 29
  • 327
  • 400
anderi
  • 767
  • 2
  • 11
  • 18

3 Answers3

14

This worked for me:

<TextBox.Text>
    <Binding RelativeSource="{RelativeSource Self}" Path="Text" UpdateSourceTrigger="LostFocus">
      <Binding.ValidationRules>
        <Filters:IntegersOnlyValidator/>
      </Binding.ValidationRules>
   </Binding>
 </TextBox.Text>
anderi
  • 767
  • 2
  • 11
  • 18
2

Your code-behind should be as independent of the GUI as possible, so I would recommend you to create a property and bind to that. When you want to pass the text to the method, just pass the value of the property.

svick
  • 236,525
  • 50
  • 385
  • 514
  • but if I have, lets say 10 textboxes , I need to create property for each one? I don't think it's effective. – anderi Jun 04 '11 at 11:52
  • @anderi, yes, that's right. The memory used for 10 string properties is 40 bytes (on 32-bit .Net) does that seem like wasting memory to you? Or do you mean something else by “effective”? – svick Jun 04 '11 at 11:57
  • anyway, there is no way to solve it without property binding? – anderi Jun 04 '11 at 12:33
  • @anderi, I don't know, but even if there was a way, I think property binding would be a better way. – svick Jun 04 '11 at 12:39
  • 1
    @anderi: are these 10 text boxes in a collection? Or are there 10 static text boxes on a form? A usual WPF strategy with any collection is to use some `ItemsControl` and reuse `DataTemplate`s with bindings. If you just have static text boxes, then yeah 1:1 binding. Might take a little up front work, but worth it in the end. – user7116 Jun 04 '11 at 14:54
2

You could bind to just any string, e.g. create one as the source for the binding:

xmlns:sys="clr-namespace:System;assembly=mscorlib.dll"
  <TextBox>
    <TextBox.Text>
      <Binding Path=".">
        <Binding.Source>
          <sys:String>Default Text</sys:String>
        </Binding.Source>
        <Binding.ValidationRules>
          <!-- Validation Rules -->
        </Binding.ValidationRules>
      </Binding>
    </TextBox.Text>
  </TextBox>
H.B.
  • 166,899
  • 29
  • 327
  • 400