如何随机定位按钮?

时间:2016-03-23 19:04:43

标签: c# visual-studio xaml button dynamic

如何在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 个答案:

答案 0 :(得分:1)

您需要在Button上设置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));
        }
    }
}

我希望这会有所帮助。 :)