我有功能:
private string[] Letters = new string[11] {"", "A", "B", "C", "D", "E","F", "G","H", "I", "J"};
private void GenerateGameMap()
{
int LocA = 5;
int LocB = 5;
for(int i = 1; i < 12; i++)
{
for(int i2 = 1; i2 < 12; i2++)
{
Canvas canvas = new Canvas();
canvas.Width = 26;
canvas.Height = 26;
canvas.Margin = new Thickness(LocA + 1, LocB + 1, 0, 0);
Border border = new Border();
border.BorderThickness = new Thickness(2);
if (i == 1 || i2 == 1)
{
Label label = new Label();
label.FontFamily = new FontFamily("Arial");
label.FontSize = 20;
label.Foreground = Brushes.White;
label.Margin = new Thickness(-1, -2, 0, 0);
label.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
label.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
if(i == 1)
{
if(i2 > 1)
{
label.Content = Litery[i2 - 1];
}
}else
{
if(i2==1)
{
label.Content = (i - 1).ToString();
}
}
border.BorderBrush = Brushes.Gold;
canvas.Background = Brushes.Black;
canvas.Children.Add(label);
}else
{
border.BorderBrush = Brushes.CadetBlue;
canvas.Background = Brushes.BurlyWood;
}
if(i > 1 && i2 > 1 )
{
canvas.Name = Letters[i2 - 1] + (i - 1).ToString();
canvas.MouseLeftButtonUp +=canvas_MouseLeftButtonUp;
}
border.Width = 28;
border.Height = 28;
border.Margin = new Thickness(LocA, LocB, 0, 0);
LocA+=30;
MainGameCanvas.Children.Add(canvas);
MainGameCanvas.Children.Add(border);
if(i2 == 11)
{
LocA = 5;
}
}
LocB += 30;
}
}
这个功能一切都很好。但是当我想找到帆布时:
private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
string canvasName = Text1.Text + Text2.Text;
var GameObject = MainGameCanvas.FindName(canvasName);
Canvas SelectedGameobject = GameObject as Canvas;
SelectedGameobject.Background = Brushes.YellowGreen;
}
我收到错误'对象引用没有在对象的实例上设置'在行“SelectedGameobject.Background = Brushes.YellowGreen;”中。还有其他方法可以找到这种控制吗?正如我所说,我确信函数GenerateGameMap()正在进行核心工作。