在我的WPF应用程序中,我有两个文本框,我正在寻找以下内容:
如果用户在textbox1
上输入了内容,我希望应用程序能将相同的值放入textbox2
中。
<TextBox x:Name="textbox1"/>
<TextBox x:Name="textbox2"/>
有没有一种优雅的方法来做到这一点?
<TextBox x:Name="textbox1" />
<TextBox x:Name="textbox2" Text="{Binding ElementName=textbox1, Path=Text}"/>
textbox2
的 Text
属性与 textbox1
的 Text
属性绑定。无论您在textbox1
中进行的更改,都会自动反映在textbox2
中。<TextBox x:Name="textbox1" Text="{Binding TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBox x:Name="textbox2" Text="{Binding TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
并添加以下C#类:
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));
}
}
MySimpleViewModel
与实际视图连接起来。但是,如果你有问题,我当然可以展示一下。另一个选择:
这也可以实现同样的功能
简单的方式:C#
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
textBox2.Text = textBox1.Text;
}
textbox2
允许输入,那么您需要更具体地说明您的规则。例如,如果textbox2
已经包含了一些用户输入文本,那么应该发生什么? - musefan