窗口上建立了一个TextBox接收用户输入,输入为int型,int x表示用户要添加x个button并且显示出来。想法师在一个StackPanel上添加用户需要个数的Button控件。但是对C#不熟悉,总是显示不出来。因为button的个数动态增加或者减少,所以没法在XAML里面写。代码如下:
public void pro_click(object sender, RoutedEventArgs e)
        {
            x = int.Parse(amount.Text);
            StackPanel sp = new StackPanel();
            Button[] btn = new Button[x];
            Ellipse[] el = new Ellipse[x];
            for (int i = 0; i < x; i++)
            {
                btn[i] = new Button();
                el[i] = new Ellipse();
                el[i].Width = 50;
                el[i].Height = 50;
                el[i].DataContext = "el1";
                btn[i].Background=new SolidColorBrush(Colors.AliceBlue);
                btn[i].Width = 50;
                btn[i].Height = 50;
                abc.Children.Add(el[i]);
            } 
        }
其中abc是在xmal里面声明的canvas:
<Canvas Name="abc">
            </Canvas>在上面的代码中无论是button btn还是ellipse el都在MainWindow中显示不出来……
请教各位大人该如何写……
比较小白,因为要做毕业设计才学的WPF,快到中期答辩了很多问题还是解决不了……先谢谢了

解决方案 »

  1.   


     <StackPanel Name="abc">      
            <Button  Name="button1" Click="Button_Click">
                click here!
            </Button>
        </StackPanel>Button[] btn = new Button[2];
                for (int i = 0; i < 2; i++)
                {
                    btn[i] = new Button();               
                    btn[i].Background = new SolidColorBrush(Colors.AliceBlue);
                    btn[i].Width = 50;
                    btn[i].Height = 50;
                    abc.Children.Add(btn[i]);
                } 
      

  2.   


        <Canvas x:Name="parent">
            <Canvas x:Name="right" Width="150" Height="400" Canvas.Left="350" Canvas.Top="0" Background="AliceBlue">
                <Button Canvas.Left="35" Canvas.Top="90" Content="添加" Height="30" Name="btnAdd" Width="75" Click="btnAdd_Click" />
                <Button Canvas.Left="35" Canvas.Top="190" Content="清空" Height="30" Name="btnClear" Width="75" Click="btnClear_Click" />
            </Canvas>
            <Canvas x:Name="left" Width="349" Height="400" Canvas.Left="0" Canvas.Top="0" Background="AntiqueWhite">
            </Canvas>
        </Canvas>        private void btnAdd_Click(object sender, RoutedEventArgs e)
            {
                Button btn = new Button();
                Ellipse el = new Ellipse();//创建一个椭圆 
                el.Width = 30;//宽度为30px 
                el.Height = 30;//高度为30px 
                btn.Width = 50;
                btn.Height = 50;
                el.Fill = new SolidColorBrush(Colors.Orange);//设置椭圆填充色为橙色 
                el.Stroke = new SolidColorBrush(Colors.Black);//设置椭圆边框色为黑色 
                el.StrokeThickness = 2;//设置边框粗细为2px             #region  设置你自己想放的位置
                Random ra = new Random();//创建一个随机数 
                double x, y;
                x = ra.NextDouble() * 300;
                y = ra.NextDouble() * 350;//设置椭圆的x,y的位置为随机数 
                double x1 = ra.NextDouble() * 100;
                double y1 = ra.NextDouble() * 135;
                el.SetValue(Canvas.LeftProperty, x);//定椭圆的位置
                el.SetValue(Canvas.TopProperty, y);
                btn.SetValue(Canvas.LeftProperty,x1);//定按钮的位置
                btn.SetValue(Canvas.LeftProperty, y1);
                #endregion             left.Children.Add(el);//在left中添加椭圆 
                left.Children.Add(btn);        }        private void btnClear_Click(object sender, RoutedEventArgs e)
            {
                left.Children.Clear();//清空left中所有的子节点元素
            }
      

  3.   

    不用动态在cs里添加button,只需在cs里定义一个List集合,然后在xaml中使用itemscontrol绑定展现出来Xaml代码:
    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
      <DockPanel>
        <!--输入数字更改,显示Button数目自动更改-->
        <TextBox DockPanel.Dock="Top" Height="23" Text="{Binding Num,UpdateSourceTrigger=PropertyChanged}"/>
        <ItemsControl  ItemsSource="{Binding Buttons}">
          <ItemsControl.ItemTemplate>
            <!--列表项的模板显示为Button-->
            <DataTemplate>
              <Button Content="{Binding Content}"/>
            </DataTemplate>
          </ItemsControl.ItemTemplate>
          <!--显示所有按钮的容器-->
          <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
              <StackPanel></StackPanel>
            </ItemsPanelTemplate>
          </ItemsControl.ItemsPanel>
        </ItemsControl>
      </DockPanel>
    </Window>cs代码:using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;using System.ComponentModel;
    using System.Collections.ObjectModel;namespace WpfApplication1
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window ,INotifyPropertyChanged
        {
            public ObservableCollection<ButtonModel> _buttons;
            public ObservableCollection<ButtonModel> Buttons
            {
                get
                {
                    return _buttons;
                }
            }        private int _Num;        public int Num
            {
                get { return _Num; }
                set 
                {
                    if (_Num == value)
                        return;
                    _Num = value;                // 数字更改,重新生成Buttons列表
                    if (_buttons != null)
                        _buttons.Clear();
                    else
                        _buttons = new ObservableCollection<ButtonModel>();                for (int i = 1; i <= _Num; i++)
                    {
                        _buttons.Add(new ButtonModel {Index=Num,Content="按钮" + i });
                    }                RaisePropertyChanged("Buttons");
                    RaisePropertyChanged("Num");            }
            }
            
            public MainWindow()
            {
                InitializeComponent();            this.DataContext = this;
            }        #region INotifyPropertyChanged 实现接口以通知页面更改
            public event PropertyChangedEventHandler PropertyChanged;
            protected virtual void RaisePropertyChanged(string propertyName)
            {
                VerifyPropertyName(propertyName);            var handler = PropertyChanged;            if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(propertyName));
                }
            }        public void VerifyPropertyName(string propertyName)
            {
                var myType = this.GetType();
                if (myType.GetProperty(propertyName) == null)
                {
                    throw new ArgumentException("Property not found", propertyName);
                }
            }
            #endregion
        }    /// <summary>
        /// 按钮属性的Model
        /// </summary>
        public class ButtonModel
        {
            public int Index { get;set; }
            public string Content { get; set; }
            //通过按钮绑定ICommand还可以实现按钮处理方法的绑定,此例中没实现这部分功能
            public System.Windows.Input.ICommand ButtonCommand{get;set;}
        }
    }