我有一个包含一堆按钮的 UniformGrid,当 UniformGrid 第一次显示它时,它会循环显示每个按钮的动画。这一切都很好,但是当用户按下某个按钮时,所有按钮都会从网格中删除,并且会在其中创建一些新按钮并再次设置动画。
这是我在代码中创建按钮的方式
int ModelsAnimateIndex = 0; // Index of button to animate
private void GetModels()
{
DirectoryInfo di = new DirectoryInfo(Globals.ModelsPath);
FileInfo[] fis = di.GetFiles();
// ugModels is the UniformGrid
switch (fis.Length)
{
case 1:
ugModels.Rows = 1;
ugModels.Columns = 1;
break;
case 2:
ugModels.Rows = 1;
ugModels.Columns = 2;
break;
case 3:
case 4:
ugModels.Rows = 2;
ugModels.Columns = 2;
break;
case 5:
case 6:
ugModels.Rows = 2;
ugModels.Columns = 3;
break;
case 7:
case 8:
case 9:
ugModels.Rows = 3;
ugModels.Columns = 3;
break;
default:
break;
}
foreach (FileInfo s in fis)
{
ugModels.Children.Add(new Button()
{
Background = ThemeColour, // SolidBrush
Foreground = new SolidColorBrush(Colors.White),
Name = "btn" + s.Name.Split('.')[0].Replace(" ",""),
Style = MainButtonStyle, // Button Style
Content = s.Name.Split('.')[0]
});
}
}
现在按钮单击事件开始为新创建的按钮设置动画
private void btnModelSelect_Click(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
sbShowMenuButton.Completed += new EventHandler(sbShowModels_Completed);
Storyboard.SetTargetName(sbShowMenuButton.Children[0], ((Button)ugModels.Children[ModelsAnimateIndex]).Name);
Storyboard.SetTargetName(sbShowMenuButton.Children[1], ((Button)ugModels.Children[ModelsAnimateIndex]).Name);
Storyboard.SetTargetName(sbShowMenuButton.Children[2], ((Button)ugModels.Children[ModelsAnimateIndex]).Name);
sbShowMenuButton.Begin((Button)ugModels.Children[ModelsAnimateIndex]); // Error is here
}
当第一个按钮尝试设置动画时,出现以下错误
在“System.Windows.Controls.Button”的名称范围内找不到“btnTestModel”名称。