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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With