Silverlight 在页面上动态生成控件
public partial class dynamicControl : UserControl
{
public dynamicControl()
{
InitializeComponent();
Button b = new Button();
b.Height = 23;
b.Width = 100;
b.HorizontalAlignment = HorizontalAlignment.Left;
//b.Margin = new Thickness(0);
b.Click += buttonClick;
b.Content = DateTime.Now;
b.Tag = "b button" + DateTime.Now.ToString();
LayoutRoot.Children.Add(b);
}
private void buttonClick(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
MessageBox.Show(b.Tag.ToString());
}
private void button1_Click(object sender, RoutedEventArgs e)
{
StringBuilder xaml = new StringBuilder();
xaml.Append("<TextBlock ");
xaml.Append("xmlns=\"http://schemas.microsoft.com/client/2007\" ");
xaml.Append(" FontWeight=\"Bold\" Text=\"动态创建XAML对象\" />");
//创建TextBlock
TextBlock tb = (TextBlock)XamlReader.Load(xaml.ToString());
LayoutRoot.Children.Add(tb);
xaml = new StringBuilder();
xaml.Append("<Button ");
xaml.Append("xmlns=\"http://schemas.microsoft.com/client/2007\" ");
xaml.Append(" Content=\"a Button\" Name=\"btn1\" Tag=\"a tag\"/>");
//创建TextBlock
Button b = (Button)XamlReader.Load(xaml.ToString());
b.Click += buttonClick;
LayoutRoot.Children.Add(b);
}
}
{
public dynamicControl()
{
InitializeComponent();
Button b = new Button();
b.Height = 23;
b.Width = 100;
b.HorizontalAlignment = HorizontalAlignment.Left;
//b.Margin = new Thickness(0);
b.Click += buttonClick;
b.Content = DateTime.Now;
b.Tag = "b button" + DateTime.Now.ToString();
LayoutRoot.Children.Add(b);
}
private void buttonClick(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
MessageBox.Show(b.Tag.ToString());
}
private void button1_Click(object sender, RoutedEventArgs e)
{
StringBuilder xaml = new StringBuilder();
xaml.Append("<TextBlock ");
xaml.Append("xmlns=\"http://schemas.microsoft.com/client/2007\" ");
xaml.Append(" FontWeight=\"Bold\" Text=\"动态创建XAML对象\" />");
//创建TextBlock
TextBlock tb = (TextBlock)XamlReader.Load(xaml.ToString());
LayoutRoot.Children.Add(tb);
xaml = new StringBuilder();
xaml.Append("<Button ");
xaml.Append("xmlns=\"http://schemas.microsoft.com/client/2007\" ");
xaml.Append(" Content=\"a Button\" Name=\"btn1\" Tag=\"a tag\"/>");
//创建TextBlock
Button b = (Button)XamlReader.Load(xaml.ToString());
b.Click += buttonClick;
LayoutRoot.Children.Add(b);
}
}