Silverligth动态控件例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Dynamic_Control_Creation
{
    public partial class Page : UserControl
    {
        private enum Platform  { Web, Desktop };
        private StackPanel sp;
        public Page()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(Page_Loaded);
        }

        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Web.Checked += new RoutedEventHandler(RB_Checked);
            Desk.Checked += new RoutedEventHandler(RB_Checked);
        }

        void RB_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton rb = e.OriginalSource as RadioButton;
            if (rb.Content.ToString().ToUpper() == "WEB")
            {
                SetChoices(Platform.Web);
            }
            else
            {
                SetChoices(Platform.Desktop);
            }
        }

        private void SetChoices(Platform whichPlatform)
        {
            if (sp == null)
            {
                sp = new StackPanel();
                LayoutRoot.Children.Add(sp);
            }
            else
            {
                sp.Children.Clear();
            }
            sp.Orientation = Orientation.Horizontal;
            sp.SetValue(Grid.RowProperty, 1);
            sp.SetValue(Grid.ColumnProperty, 3);
           
            if (whichPlatform == Platform.Desktop)
            {
                CreateCheckBox("Winform", sp);
                CreateCheckBox("WPF", sp);
            }
            else
            {
                CreateCheckBox("AJAX", sp);
                CreateCheckBox("Silverlight", sp);
            }
          
        }

        private void CreateCheckBox(
            string txt,
            StackPanel thePanel)
        {
            CheckBox cb = new CheckBox();
            cb.Content = txt;
            cb.Height = 30;
            cb.Width = 90;
            cb.Checked += new RoutedEventHandler(cb_Checked);
            cb.Unchecked += new RoutedEventHandler(cb_Checked);
            thePanel.Children.Add(cb);
        }

        void cb_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = e.OriginalSource as CheckBox;
            if (cb != null)
            {
                if (cb.IsChecked == true)
                {
                    Messages.Items.Add(cb.Content.ToString() + " selected");
                }
                else
                {
                    Messages.Items.Add(cb.Content.ToString() + " cleared");
                }
            }
        }
    }
}

关于作者: 王昕(QQ:475660) 在广州工作生活30余年。十多年开发经验,在Java、即时通讯、NoSQL、BPM、大数据等领域较有经验。
目前维护的开源产品:https://gitee.com/475660
原文地址:https://www.cnblogs.com/starcrm/p/1348454.html