Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to two textboxes simultaneously [duplicate]

Tags:

c#

wpf

xaml

In my WPF app I have two textboxes, and I am looking for the following:

I want that if the user writes something on textbox1 the app would put the same value into textbox2,

<TextBox x:Name="textbox1"/>
<TextBox x:Name="textbox2"/>

Is there an elegant way to do this?


1 Answers

The following will work:

<TextBox x:Name="textbox1" />
<TextBox x:Name="textbox2" Text="{Binding ElementName=textbox1, Path=Text}"/>

Now what this does is that the Text property of textbox2 is bound to the Text property of textbox1. Every change you do in textbox1 will automatically be reflected in textbox2.


EDIT: Real Requirements

Based on your comment, here's a solution which might be what you want to do:

<TextBox x:Name="textbox1" Text="{Binding TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBox x:Name="textbox2" Text="{Binding TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

and add this C# class:

public class MySimpleViewModel : INotifyPropertyChanged
{
    private string theString = String.Empty;

    public string TheString
    {
        get => this.theString;
        set
        {
            if(this.theString != value)
            {
                this.RaisePropertyChanged();
                this.theString = value;
            }
        }
    }
        
    public event PropertyChangedEventHandler PropertyChanged;

    public virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

What I did not show is how to wire up the MySimpleViewModel with the actual view. However, if you have problems with that, I can certainly show that as well.

Hope it helps.

like image 144
Thomas Flinkow Avatar answered Sep 03 '26 16:09

Thomas Flinkow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!