Writing to two textboxes simultaneously [duplicate

2019-07-05 01:07发布

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?

标签: c# wpf xaml
2条回答
Juvenile、少年°
2楼-- · 2019-07-05 01:29

Another alternative for you

This will also do samething

Simple way: C#

  private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        textBox2.Text = textBox1.Text;
    }
查看更多
地球回转人心会变
3楼-- · 2019-07-05 01:38

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.

查看更多
登录 后发表回答