I have a user control as under where I have exposed a public property. Based on the property value set, I am trying to creat the labels at runtime
public partial class MyUserControl : UserControl
{
public int SetColumns { get; set; }
public MyUserControl()
{
InitializeComponent();
myGrid.Children.Clear();
myGrid.RowDefinitions.Add(new RowDefinition());
for (int i = 0; i < SetColumns; i++)
{
//Add column.
myGrid.ColumnDefinitions.Add(new ColumnDefinition());
}
for (int j = 0; j < SetColumns; j++)
{
Label newLabel = new Label();
newLabel.Content = "Label" + j.ToString();
newLabel.FontWeight = FontWeights.Bold;
newLabel.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
Grid.SetRow(newLabel, 0);
Grid.SetColumn(newLabel, j);
myGrid.Children.Add(newLabel);
}
}
}
This user control is being invoked from a window as under
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:WpfApplication2"
Title="MainWindow" Width="300" Height="300">
<Grid >
<local:MyUserControl SetColumns="10"></local:MyUserControl>
</Grid>
</Window>
The problem is that, the value is always coming as zero(0) in the user control property and hence nothing is getting created.
What mistake I am making? Please help.
SetColumnsis a property, you’re reading it’s value in constructor, but all properties are set AFTER constructor call. So externally XAML parser does something like this:Try updating your control in
SetColumnsproperty setter: