WPF: How can I update Text in TextBox in code without losing binding information?

AxD 661 Reputation points
2021-01-23T15:15:32.037+00:00

I created a validating WPF user control, derived from TextBox.

The Text property in my TextBox is bound using something like <my:MyTextBox Text={Binding ..., Mode=OneWay}. The user may update the displayed text therein, so I can further process the updated text.

When the user enters invalid text, I want to re-enter valid data into my custom TextBox using code like Text = _validText;. But when I do that, the original Binding is lost for the Text property (of course).

How can I update a TextBox's Text in code without losing the original binding information?

---
(PS: Original question was posted here. I closed the original question now after realizing that assigning text to the Text property obviously overwrites the original binding information.)

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,675 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,268 questions
{count} votes

Accepted answer
  1. AxD 661 Reputation points
    2021-01-26T09:07:25.37+00:00

    Thanks for all your replies.

    I wanted to keep invalid characters from being typed into the front-end, so the view-model could have kept their original data type (e.g. int). When the TextBox would have lost focus, I would have manually updated the source (using BindingExpression::UpdateSource())

    It doesn't look like this is possible.

    So, I changed all view-model properties to string and switched to Mode=TwoWay. And I manually convert data types later then.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bonnie DeWitt 811 Reputation points
    2021-01-24T21:46:29.903+00:00

    Change the Mode to TwoWay.


    ~~Bonnie DeWitt [MVP since 2003]
    [http://geek-goddess-bonnie.blogspot.com]1

    0 comments No comments