开发者

WPF control and parsing/binding to a given string

开发者 https://www.devze.com 2022-12-14 22:18 出处:网络
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 stri开

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 stri开发者_开发技巧ng 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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消