Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9242995
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T08:42:33+00:00 2026-06-18T08:42:33+00:00

Before I start explaining my issue, please note that my target framework is .NET

  • 0

Before I start explaining my issue, please note that my target framework is .NET 3.5.

I have a textbox whose text is bound to a viewmodel property. My requirement is that when user enters something(via keyboard as well as Mouse Paste) into the textbox, any junk characters inside it should be cleaned and the textbox should be updated with the replaced string[In the below example ‘s’ to be replaced with ‘h’].

XAMLCode:

 <Style x:Key="longTextField" TargetType="{x:Type TextBoxBase}">
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="OverridesDefaultStyle" Value="True"/>
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="AcceptsReturn" Value="True"/>
            <Setter Property="AllowDrop" Value="true"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TextBoxBase}">
                        <Border      
                      Name="Border"    
                      Padding="2"    
                      Background="Transparent"    
                      BorderBrush="LightGray"    
                      BorderThickness="1">
                            <ScrollViewer Margin="0" x:Name="PART_ContentHost"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter Property="Foreground" Value="Black"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
 <TextBox Grid.Column="1" Grid.Row="2" Text="{Binding Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}"  MinLines="3"       TextWrapping="Wrap"
                 SpellCheck.IsEnabled="True" Style="{StaticResource longTextField}"></TextBox>

ViewModel property:

     private string _value;
            public string Value
            {
                get
                {
                    return _value;
                }
                set
                {
                    if (_value == value) 
                        return;

                    _value = value;
//replaces 's' with 'h' and should update the textbox.
                    _value = _value.Replace('s','h');
                    RaisePropertyChanged(() => Value);
                }
            }

The above is simply not working for me. The view model property setter is firing…the value is getting replaced..however the textbox is not getting updated. What is confusing is that this works perfectly on .Net4.0.

Do you know why this wont work and what is a potential solution to this problem, of course other than upgrading to .NET 4.0?

My requirement:

  • User can type as well as paste anything into a multilined textbox.

  • The text can contain junk which should be changed before it comes on to the textbox.

Thanks in advance,
-Mike

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T08:42:34+00:00Added an answer on June 18, 2026 at 8:42 am

    I encountered a very similar problem where I wanted the two way binding and I was modifying the value in the ViewModel and expecting to see the update in the TextBox. I was able to get it resolved. Although I was using .NET 4.0, I basically had the same issue, so this may be worth trying out for your situation with 3.5 as well.

    Short Answer:

    What I encountered was a bug where the TextBox's displayed text was getting out of sync with the value of that TextBox's own Text property. Meleak’s answer to a similar question clued me in to this and I was able to verify this with the debugger in Visual Studio 2010, as well as by employing Meleak’s TextBlock technique.

    I was able to resolve it by using explicit binding. This required handling the UpdateSource() and UpdateTarget() issues myself in code behind (or in a custom control code as I eventually did to make it easier to reuse).

    Further Explanation:

    Here’s how I handled the explicit binding tasks. First, I had an event handler for the TextChanged event which updated the source of the binding:

    // Push the text in the textbox to the bound property in the ViewModel
    textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    

    Second, in I had an event handler for the TextBox’s Loaded event. In that handler, I registered a handler for the PropertyChanged event of my ViewModel (the ViewModel was the “DataContext” here):

    private void ExplicitBindingTextBox_Loaded(object sender, RoutedEventArgs e)
    {
        TextBox textBox = sender as TextBox;
    
        if (textBox.DataContext as INotifyPropertyChanged == null)
            throw new InvalidOperationException("...");
    
        (textBox.DataContext as INotifyPropertyChanged).PropertyChanged +=
                      new PropertyChangedEventHandler(ViewModel_PropertyChanged);
    }
    

    Finally, in the PropertyChanged handler, I cause the TextBox to grab the value from the ViewModel (by initiating the UpdateTarget()). This makes the TextBox get the modified string from the ViewModel (in your case the one with replaced characters). In my case I also had to handle restoring the user’s caret position after refreshing the text (from the UpdateTarget()). That part may or may not apply to your situation though.

        /// <summary>
        /// Update the textbox text with the value that is in the VM.
        /// </summary>
        void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            // This textbox only cares about the property it is bound to
            if (e.PropertyName != MyViewModel.ValueStrPropertyName)
                return;
    
            // "this" here refers to the actual textbox since I'm in a custom control
            //  that derives from TextBox
            BindingExpression bindingExp = this.GetBindingExpression(TextBox.TextProperty);
            // the version that the ViewModel has (a potentially modified version of the user's string)
            String viewModelValueStr;
    
            viewModelValueStr = (bindingExp.DataItem as MyViewModel).ValueStr;
    
    
            if (viewModelValueStr != this.Text)
            {
                // Store the user's old caret position (relative to the end of the str) so we can restore it
                //  after updating the text from the ViewModel's corresponding property.
                int oldCaretFromEnd = this.Text.Length - this.CaretIndex;
    
                // Make the TextBox's Text get the updated value from the ViewModel
                this.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
    
                // Restore the user's caret index (relative to the end of the str)
                this.CaretIndex = this.Text.Length - oldCaretFromEnd;
            }
    
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Before start let me tell my experience: I am experienced with C#.NET, web services,
before I start I want to point out that I tagged this question as
(Before I start, yes I have asked a similar question before; unfortunately due to
Before I start, I want to make it clear that my code is working
I get an error stating that I got an exception before start of a
Before I start explaining the problem - yes I looked in the Qt forums
Before start I have been trying to accomplish it for some time now, but
Before I start explaining the code I will first give my use case so
I'll start with the background story before explaining the problem with my code. I'm
I have been trying to ask this before, without any luck of explaining/proving a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.