简体   繁体   English

UserControl:在构造函数中使用自定义属性

[英]UserControl: use custom property in the constructor

I've this issue: 我有这个问题:

I created a custom UserControl and I added this property: 我创建了一个自定义UserControl并添加了以下属性:

public string TestString { get; set; }

and it's ok, in the Properties I'm able to edit it: 没关系,在属性中,我可以对其进行编辑:

在此处输入图片说明

Now it's the issue: I need to read this property in the Constructor of my usercontrol: to simply test this I have this code: 现在是问题所在:我需要在用户控件的构造函数中读取此属性:为了简单地进行测试,我有以下代码:

public ucnTest()
{
    InitializeComponent();
    MessageBox.Show(TestString);
}

and when I go run I got this: 当我跑步时,我得到了:

在此处输入图片说明

seems that during the constructor the value is not yet passed... how can I fix this? 似乎在构造函数期间尚未传递值...我该如何解决?

PS: if I put the message in the load event it works: PS:如果我将消息放入load事件中,它将起作用:

private void ucnTest_Load(object sender, EventArgs e)
{
    MessageBox.Show(TestString);
}

WPF/UWP rule of thumb: all visual activities should be intended to happen not before Loaded event. WPF / UWP的经验法则:所有视觉活动都应在发生Loaded事件之前发生。 Partially-loaded control can behave weirdly or even crash. 部分加载的控件可能行为异常,甚至崩溃。 So, popping a message box directly from the constructor is really-really bad idea from very beginning. 因此,从一开始就直接从构造函数中弹出消息框确实是个坏主意。

To understand what's happening, I suggest you look into the InitializeComponent() method of your forms constructor (or wherever you added your UserControl). 为了了解正在发生的事情,建议您研究一下窗体构造函数的InitializeComponent()方法(或添加UserControl的任何位置)。

You should see, that the constructor of your UserControl is called, before the value you assigned in the designer is passed to your control. 您应该看到,在设计器中分配的值传递给控件之前,已调用UserControl的构造函数。

If you really need to access the value in the constructor, you need to pass it as a parameter like so: 如果确实需要访问构造函数中的值,则需要将其作为参数传递,如下所示:

public string TestString { get; set; }
public ucnTest(string myStringValue)
{
    InitializeComponent();
    TestString = myStringValue;
    MessageBox.Show(TestString);
}

and then you need to pass "YourString" to the constructor in the InitializeComponent() method. 然后需要在InitializeComponent()方法"YourString"传递给构造函数。

EDIT: Added the property to the code 编辑:将属性添加到代码

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

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