两种方法都是通过后台编码的方式实现。
一种方法是直接申明控件,然后add。另一种是拼接XAML串,然后加载。
private void button1_Click(object sender, RoutedEventArgs e)
{
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();
stackPanel1.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 button2_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());
stackPanel1.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;
stackPanel1.Children.Add(b);
}
对于第二种方法,要注意的是
xaml.Append("xmlns=\"http://schemas.microsoft.com/client/2007\" ");
这个不能漏掉。xmlns是xml命名空间。
对于拼接XAML字符串,注意属性名是大小写敏感的。
本文转自cnn23711151CTO博客,原文链接: http://blog.51cto.com/cnn237111/626012,如需转载请自行联系原作者