2016-03-23 17 views
0

XAMLのグリッドにボタンimgをランダムに配置するにはどうすればよいですか?私はそれを試しましたが、うまくいきません!ボタンをランダムに配置する方法は?

これは私のコードです:

public void randomButton() 
    { 
     Button newBtn = new Button(); 
     newBtn.Content = "A New Button"; 
     panelButton.Children.Add(newBtn); 
     Grid.SetRow(newBtn, 1); 

     Random generator = new Random(); 
     newBtn = generator.Next(1, 100); 
    } 

答えて

1

ボタン上Grid.Row依存関係プロパティを設定する必要があります。

XAML

<Window x:Class="WpfApplication1.MainWindow" [...] Loaded="Window_Loaded"> 
    <Grid Name="grdMain"> 
     <Grid.RowDefinitions> 
      <RowDefinition/> 
      <RowDefinition/> 
      <RowDefinition/> 
     </Grid.RowDefinitions> 
    </Grid> 
</Window> 

C#

using System; 
using System.Windows; 
using System.Windows.Controls; 

namespace WpfApplication1 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     void Window_Loaded(object sender, RoutedEventArgs e) 
     { 
      //creating the button 
      Button b = new Button() { Content = "Click me!" }; 
      //when clicked, it'll move to another row 
      b.Click += (s, ea) => ChangeButtonRow(s as Button); 
      //adding the button to the grid 
      grdMain.Children.Add(b); 
      //calling the row changing method for the 1st time, so the button will appear in a random row 
      ChangeButtonRow(b); 
     } 

     void ChangeButtonRow(Button b) 
     { 
      //setting the Grid.Row dep. prop. to a number that's a valid row index 
      b.SetValue(Grid.RowProperty, new Random().Next(0, grdMain.RowDefinitions.Count)); 
     } 
    } 
} 

私はこのことができます願っています。 :)

関連する問題