です。このコードは、ここで動的にボタンを私のwpfウィンドウアプリケーションに追加します。ランダムに追加されているため、実際にrunatサーバーと呼ばれるボタンを呼び出すことはできません。ランダムに割り当てられたボタン
namespace DynamicButtons
{
public partial class Window1
{
public Window1()
{
this.InitializeComponent();
populateButtons();
}
public void populateButtons()
{
int xPos;
int yPos;
Random ranNum = new Random();
for (int i = 0; i < 4; i++)
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = ranNum.Next(100);
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(200);
yPos = ranNum.Next(300);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Name = "button" + i;
foo.Click += new RoutedEventHandler(buttonClick);
LayoutRoot.Children.Add(foo);
}
}
private void buttonClick(object sender, EventArgs e)
{
Button clicked = (Button) sender;
// something like certainWindowsButton((i)<-this has to be based on above code) = clicked.Name();
MessageBox.Show("Button's name is: " + clicked.Name);
}
}
}
アプリケーションはボタンがランダムに割り当てられている実行されるたびに、私が欲しいのは、私が背後にあるコードからそれらと対話することができる方法です。
ので
foo.Name = "button" + i;
は、番号をクリックされたとき、またはどちらかのボタンを意味し、それに割り当てられているが、どのように私は、コードでそのボタンと対話することができますか?
private void buttonClick(object sender, EventArgs e)
{
Button clicked = (Button) sender;
// something like certainWindowsButton((i)<-this has to be based on above code) = clicked.Name();
MessageBox.Show("Button's name is: " + clicked.Name);
}
}
私はそれが合理的であることを望みます。
は、設計レベルで起こっていただきました!あなたの感覚を与えるために:
これらの灰色の正方形の各
は、各ボタンがランダムに指定された名前と番号とするたびに割り当てられているボタンでアプリケーションがこれらのボタンを実行します別の番号が割り当てられます。
数字が割り当てられているときに、そのボタンのイベントを発生させることができます。そのようにランダムボタンを数1が割り当てられている
、この数1を取ると
private void buttonClick(object sender, EventArgs e)
if
{
button1_Click = clicked.Name(strip away "button" and make sure the (variableNumber leftover matches button(1)_Click);
}
else
button2
などなど
その後、私のボタンのイベントをトリガーするに割り当てます。
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("yay each randomly assigned button now correlates with a real button event");
}
}
}
あなたはあなたが望む名前を与えていませんか?イベントハンドラへの送信者パラメータの全体的なポイントは、イベントをトリガしたオブジェクト、つまりクリックされたボタンが含まれているということです。 – Chris
ええ、どうにかボタン1を何かにバインドしますかコードの背後にある?たとえば "button1"にコンテンツを開くには、button1を押したときにコードの中でどのように呼び出すことができますか? –
私はボタンを押したときに表示されるボタン名を変更します。メッセージボックスを表示するボタンが1つだけで、別のウィンドウを開くボタンが必要な場合は、どのボタンを押しても同じように表示されます。二? –