2012-06-24 21 views
1

添加在鼠標點擊點控制我有我的計劃,一些按鈕添加到它在運行時(如面板添加標籤爲問題在本網站)一個WrapPanel。現在我想的按鈕之間單擊並在鼠標位置添加一個新的按鈕clicked.but我不知道我怎樣才能按鈕或如何獲取放置鼠標點擊之前該按鈕的子指數之間的鼠標位置!如何WrapPanel

我應該說我必須使用WrapPanel,我不想使用Canvas或其他容器。

感謝您的幫助..

回答

0

使用此代碼MouseClick事件您WrapPanel的:

Button b = new Button(); 
b.Location = new Point(MousePosition.X-this.ClientSize.Width, MousePosition.Y-this.ClientSize.Height); 
this.Controls.Add(b); 

更新:

Button b = new Button(); 
b.Location = new Point(MousePosition.X - this.ClientSize.Width, MousePosition.Y - this.ClientSize.Height); 
this.WrapPanel1.Controls.Add(b); 

更新2:

Button mybutton = new Button(); 
     mybutton.Content = "This is wpf button"; 
     Point mousePoint = this.PointToScreen(Mouse.GetPosition(this)); 
     MainWindow win = new MainWindow(); 
     win.Left = mousePoint.X; 
     win.Top = mousePoint.Y; 
     mybutton.PointToScreen(new Point(win.Left,win.Top)); 
     wrapPanel1.Children.Add(mybutton); 
+0

感謝您的回答,但在wpf中沒有MouseClick for WrapPanel和位置屬性的按鈕。我認爲你的代碼只適用於WinForms。 – sheida

+0

我以爲你在談論WinForms。所以看到我更新 – aliboy38

+0

我寫這篇文章的代碼WrapPanel的的MouseDown和得到這個例外在第7行:「此Visual未連接到PresentationSource」 – sheida

0

我的問題通過此代碼解決:

private void wpContainer_MouseDown(object sender, MouseButtonEventArgs e) 
    { 
     Button newButton = new Button() 
         { 
          Content= wpContainer.Children.Count, 

          Margin = new Thickness() 
          { 
           Right = 10, 

           Left = 10, 
          } 
         }; 

     var mousePosition = Mouse.GetPosition(wpContainer); 

     int index=0; 

     foreach (var child in wpContainer.Children) 
     { 
      Button currentButton = (child as Button); 

      if (currentButton==null) 
       continue; 

      Point buttonPosition = currentButton.TransformToAncestor(wpContainer).Transform(new Point(0, 0)); 

      if (buttonPosition.X > mousePosition.X && buttonPosition.Y+currentButton.ActualHeight > mousePosition.Y) 
      { 
       wpContainer.Children.Insert(index, newButton); 

       return;      
      } 

      index++; 
     } 

     if(wpContainer.Children.Count==0 || index==wpContainer.Children.Count) //no items where detected so add it to the end of the Children 
      wpContainer.Children.Add(newButton); 
    }