无法在WPF中删除运行时生成的控件

时间:2013-08-16 09:37:27

标签: wpf xaml wpf-controls

我似乎无法删除在运行时生成的按钮。

以下是生成按钮的代码:

void testArea(Object s, RoutedEventArgs e)
    {
        System.Windows.Controls.Button myButton = new System.Windows.Controls.Button();
        myButton.Name = "runtimeGeneratedButton";
        myButton.Content = "deleteMe";
        myButton.Click+= new RoutedEventHandler(deleter);
        operationsPannel.Children.Add(myButton);
    }

以下是应该删除生成按钮的代码:

private void deleter(object s, RoutedEventArgs args)
    {
        operationsPannel.Children.Remove(operationsPannel.FindName("runtimeGeneratedButton") as System.Windows.Controls.Button);
    }

1 个答案:

答案 0 :(得分:1)

对于您在代码中创建的控件,如果要按名称查找它们,则需要在当前名称范围内RegisterName

operationsPannel.Children.Add(myButton);
operationsPannel.RegisterName("runtimeGeneratedButton", myButton);

这是由XAML解析器

自动完成的