views:

41

answers:

2

Hey guys,

I am new to WPF and am trying to create a WPF control that displays a string (which will always be a number) in a particular way. There will be three different text fields on the control and the string needs to be split up into three different components following these rules:

Lets say you have the string "1.5678". The control needs to display the string as follows, in the three text fields:
textField1 = "1.5"
textField2 = "67"
textField3 = "8"

The rule is that textField3 will always contain the last character, textField2 will contain the two chars before the last one, and textField1 will contain the rest. Here are some more examples:

"145.670"
textField1 = "145."
textField2 = "67"
textField3 = "0"

"15.839"
textField1 = "15."
textField2 = "83"
textField3 = "9"

Assume that the string will always contain at least 4 characters.

Now, is there a way I can use the new WPF binding features to do this for me automatically? Can I bind the WPF control to some property that contains the string and have the text boxes just display it as I described?

Thanks

A: 

You could do this via binding (to a single property), by using an IValueConverter for your binding. The docs for the IValueConverter give a sample implementation.

Each control could have a converter that specifies which portion to display, and your text box binding would then just do the conversion for you.

Note that you could do this by either using three separate converter classes, or one class with an enum that specified which portion to display (which would still require three unique instances).

Reed Copsey
Using a value converter would not allow you to use two-way binding because it is not possible to determine the entire value based on just a part of it that was changed.
Aviad P.
No, but he specifically only mentioned DISPLAY of the string - he did not specify that he needed to edit the string.
Reed Copsey
A: 

Yes, that should be possible.

  1. Create a user control.

  2. Create a dependency property (Text/TextProperty) in your control that will contain the string (you can later data-bind to this property when using your control).

  3. Create a converter that converts the full string into the part that is necessary (based on some property, e.g. PartNumber, of the converter).

  4. In the XAML of your control, create three instances of your converter with different part numbers as static resources.

  5. Then use a binding ({Binding ElementName=myControl, Path=Text, Converter={StaticResource FirstPartConverter}}), which binds the text field in your control to the dependency property, using the correct converter.

Feel free to ask in the comments if any step is unclear.

Heinzi