The reason why nothing is displayed is because there is no content set to your
UserControl
.
The below code will display Hello:
UserControl u1 = new UserControl();
u1.Height = 100;
u1.Width = 100;
u1.Content = "Hello"
uniformgrid1.Children.Add(u1);
Just to add one more example, let's say you want to add an
Image
into your
UserControl
.
UserControl u1 = new UserControl();
u1.Height = 100;
u1.Width = 100;
Image img = new Image();
img.Source = new BitmapImage(new Uri(@"C:\Windows.png",UriKind.RelativeOrAbsolute));
u1.Content = img;
uniformgrid1.Children.Add(u1);
Update :
Comment from kiranvls:
Hi Tarun, In the above code user control is dynamically created with image as content. Now i have added a event handler u1.MouseMove +=new MouseEventHandler(uc_MouseMove); private void uc_MouseMove(object sender, MouseEventArgs e) { Here iam unable to access the dynamically created user control object(u1); } how to get object name in event handler plz help me.
Answer:
Sure you can access it. Check out the argument "e" in the MouseMove eventhanlder. It's rich in properties including the Source property. You have to cast the Source property to UserControl. Here is what you have to do:
void uc_MouseMove(object sender, MouseEventArgs e)
{
UserControl uControl = (UserControl)e.Source;
}
Hope this helps.