有几种方法可以做到这一点。最简单的方法是使用 String 属性并在 UserControl 中实现 INotifyPropertyChanged。
为了说明,您将拥有像这样的 UserControl:
/// <summary>
/// Interaction logic for TextBoxUsercontrol.xaml
/// </summary>
public partial class TextBoxUsercontrol : UserControl, INotifyPropertyChanged
{
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
public TextBoxUsercontrol()
{
DataContext = this;
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
}
现在您的 UserControl 中的 TextBox 必须像这样将自己绑定到您的 Text 属性:
<TextBox Text="{Binding Text}" />
然后在您的 WPF 表单中,您将声明您的 UserControl 和一个按钮来处理单击,如下所示:
<local:TextBoxUsercontrol x:Name="textBox" />
<Button Click="ButtonBase_OnClick" >Add Text</Button>
最后,在您的 Click 处理程序中:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
textBox.Text = "Hello!";
}
在向您展示了解决方案后,我给您的提问技巧打了 1 分(满分 5 分)。您可以更具体地提出问题并提供示例代码 sn-ps,就像我所做的那样,无需我们下载您的整个解决方案从我们必须等待的站点下载它(更不用说我们大多数人都对下载未知文件有安全意识)。
祝你好运。