我正在尝试将按钮的内容传递给另一个类,这些按钮是动态创建的,这意味着内容不同。当我尝试访问button.content时,它说我无法访问它在当前上下文中不存在的原因。
我在方法1中使用了这个代码,我在A类中运行。
foreach (string lines in textfile)
{
if (Checker == CheckerCounter)
{
marginbottom += 150;
left = 0;
}
string threeletters = additional.Substring(0, 3);
if (additional.Contains(passedinfoArray[2]))
{
Button DynamicBtn = new Button
{
Content = threeletters,
Width = 100,
Height = 56,
Foreground = new SolidColorBrush(Colors.White),
Background = new SolidColorBrush(Colors.Black),
FontSize = 24,
Margin = new Thickness(-900 + left, 0, 0, 400 - marginbottom),
};
left += 300;
DynamicChecker += 1;
Maingrid.Children.Add(DynamicBtn);
DynamicButton1.Click += new System.Windows.RoutedEventHandler(DynamicBtn_Click);
路由方法2也在A类中。
private void DynamicBtn_Click(object sender, RoutedEventArgs e)
{
Array[0] = DynamicBtn1.Content; //code that doesnt work
classB bClass = new classB(Array);
this.Close();
bClass.ShowDialog();
}
我需要将点击按钮的内容作为已创建的字符串存储到数组中,但我无法动态访问所点击按钮的内容。
我该如何解决这个问题?
答案 0 :(得分:4)
由于按钮是举起事件的按钮,因此只需将sender
投射到所需的类型。
private void Dynamicbutton1_Click(object sender, RoutedEventArgs e) {
var DynamicButton1 = sender as Button;//this casts the sender to the desired type
passedinfoArray[0] = DynamicButton1.Content as string; //Or DynamicButton1.Content.ToString();
classB bClass = new classB(passedinfoArray);
this.Close();
showTour.ShowDialog();
}