Reputation: 8003
I've this issue:
I created a custom UserControl
and I added this property:
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:
private void ucnTest_Load(object sender, EventArgs e)
{
MessageBox.Show(TestString);
}
Upvotes: 0
Views: 389
Reputation: 5369
WPF/UWP rule of thumb: all visual activities should be intended to happen not before Loaded
event. 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.
Upvotes: 1
Reputation: 512
To understand what's happening, I suggest you look into the InitializeComponent() method of your forms constructor (or wherever you added your 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.
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.
EDIT: Added the property to the code
Upvotes: 0