none
请问怎样在Canvas中增加随机个数的子控件 RRS feed

  • 问题

  • 请问怎样在Canvas中增加随机个数的子控件
    比如,多个Rectangle或者Canvas等
    在XAML中绑定了集合变量中保存了Canvas的数量

    例如:
        public class TestRecordings : DependencyObject, ICloneable
        {
            public static readonly DependencyProperty RecordingsProperty = DependencyProperty.Register("Recordings", typeof(ObservableCollection<Canvas>), typeof(TestRecordings), null);
    
            public TestRecordings ()
            {
                this.Recordings = new ObservableCollection<Canvas>();
            }
    
            public ObservableCollection<Canvas> Recordings
            {
                get
                {
                    return (ObservableCollection<Canvas>)base.GetValue(RecordingsProperty);
                }
                set
                {
                    base.SetValue(RecordingsProperty, value);
                }
            }
        }
    我想在Canvas中绑定Recordings然后显示出来其中的内容,
    多个Canvas,自动根据集合中Canvas的属性排列,
    也就是说子控件的位置由其自己的属性决定,父控件只是个容器。

    请帮忙分析怎样才能做到,非常感谢。



    2009年4月9日 3:16

答案

  • 你好

    你是不是想根据数据源在Canvas中动态显示多个Rectangle?如果是可以参考下面的例子试试。

      public class TestRecordings : DependencyObject

        {

           private Random random = new Random ();

     

           public static readonly DependencyProperty RecordingsProperty = DependencyProperty .Register("Recordings" , typeof (ObservableCollection <Record >), typeof (TestRecordings ), null );

     

           public TestRecordings()

           {

               this .Recordings = new ObservableCollection <Record >();

               for (int i = 0; i < 10; i++)

               {            

                  this .Recordings.Add(new Record () { Left = (double )random.Next(0, 400), Top = (double )random.Next(0, 400) });

               }

           }

     

           public ObservableCollection <Record > Recordings

           {

               get

               {

                  return (ObservableCollection <Record >)base .GetValue(RecordingsProperty);

               }

               set

               {

                  base .SetValue(RecordingsProperty, value );

               }

           }

        }

     

    create a ListBox:

     

           < ListBox x : Name ="lb">

               < ListBox.ItemTemplate >

                  < DataTemplate >

                      < Canvas >

                         < Rectangle Canvas.Left ="{ Binding Left }" Canvas.Top ="{ Binding Top }" Fill ="Red" Width ="100" Height ="100"/>

                      </ Canvas >

                  </ DataTemplate >

               </ ListBox.ItemTemplate >

           </ ListBox >

     

    bind its ItemsSource to the Recordings:

     

               this .lb.ItemsSource = new TestRecordings ().Recordings;


    Microsoft Online Community Support
    2009年4月13日 9:39