繁体   English   中英

如何将字符串从用户控件传递到WPF中的父窗口?

[英]How to pass a string from user control to its parent Window in WPF?

我用文本框和按钮定制了UserControl。 我将此UC添加到主窗口,现在我希望当我单击UC中的按钮时,来自UC文本框的文本被传输到主窗口中的文本框或标签中。 如果我是对的,我应该进行自定义事件并将其绑定到某个地方或类似的东西,但是我找不到任何有用的东西,因此我很乐意提供帮助或提供良好的教程。

通过在UC中使用属性并在MainWindow中订阅此属性的propertychanged事件,您可以轻松实现所需的功能。

在UserControl中

public class UserControl : BindableBase
{

    private string textboxText;
    public string TextBoxText
    {
       get { return textboxText; }
       set { SetProperty(ref textboxText,value); }
    }

}

因此,当文本框失去焦点时,将更新属性textboxText。

在MainWindow中

public class MainWindow
{
    public UserControl UserControlInstance = new UserControl();
    public string textPropertyMainWindow;
    public MainWindow()
    {
       UserControlInstance.TextBoxText.PropertyChanged += PropertyChangedHandler;
    }

    private void PropertyChangedHandler(object obj)
    {
       textPropertyMainWindow = UserControlInstance.TextBoxText;
    }
}

希望你明白了。 如果需要任何其他帮助,请还原。

最简单的方法必须是这样,您最好进行练习,因为它基本上可以多次使用。

在类的字段中声明一个数据类型,例如,

string textwhichuserinputed;

并为Event或Method(where)中的变量分配一个值,例如:

textwhichuserinputed= UCtextBox.Text;

分配后,变量的值将设置为UCtextBox.Text。 并且在赋值之前,该值为null。

然后,之后,您可以使用用户在类中各处输入的文本。

这是您最好练习的最简单,最基本的方法。
这就是所谓的全局变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM