微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Silverlight动态加载控件的2种方法

两种方法都是通过后台编码的方式实现。

一种方法是直接申明控件,然后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字符串,注意属性名是大小写敏感的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐