I have a usercontrol:
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Name="TextBlock1" Text="Text for"></TextBlock>
</Grid>
It has a cs file:
public partial class MyUserControl: UserControl
{
public string MyProperty { get; set; }
public MyUserControl()
{
InitializeComponent();
DoSomething();
}
private void DoSomething()
{
TextBlock1.Text = TextBlock1.Text + MyProperty;
}
}
I’m trying to add this usercontrol programatically to another user control:
UserControls.MyUserControl myUserControl = new UserControls.MyUserControl();
myUserControl.MyProperty = "Something";
MyStackPanel.Children.Add(myUserControl);
I thought I’ve done something like this before without any issues, but in this case MyProperty is always null. What did I do wrong?
Your code is fine as-is except for when you are calling
DoSomething(). You should avoid GUI interaction in the constructor of a control for many reasons (not the least of which is that your property is not yet set as pointed out by Mark Hall). I do not however recommend adding different constructors just to take initial properties.You simply want to defer that call to the Loaded event of the control.
Assuming you set the event in the Xaml like this:
Your code would look like:
If you want to set the Loaded event in code it would just look like:
The it is just down to you setting all your desired properties after construction, but before the page is loaded as you are doing already.