同时写入两个文本框 [英] Writing to two textboxes simultaneously
问题描述
在我的 WPF 应用程序中,我有两个文本框,我正在寻找以下内容:
In my WPF app I have two textboxes, and I am looking for the following:
我希望如果用户在 textbox1
上写一些东西,应用程序会将相同的值放入 textbox2
,
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?
推荐答案
以下内容将起作用:
<TextBox x:Name="textbox1" />
<TextBox x:Name="textbox2" Text="{Binding ElementName=textbox1, Path=Text}"/>
现在这样做的是 Text
属性 textbox2
被绑定到 Text
属性<代码>文本框1代码>.您在 textbox1
中所做的每个更改都会自动反映在 textbox2
中.
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}" />
并添加这个 C# 类:
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));
}
}
我没有展示的是如何将 MySimpleViewModel
与实际视图连接起来.但是,如果您对此有疑问,我当然也可以证明这一点.
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.
希望有帮助.
这篇关于同时写入两个文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!