2012-01-11 103 views
0

我刚开始学习VB和Visual Studio,并且遇到了问题。我花了一天中最好的时间来寻找答案,我有一种可怕的感觉,那就是我看起来很简单的事情。无法动态添加新按钮

我正在研究Visual Studio 2010中的WPF,并试图在单击按钮时在主窗口上动态创建按钮(我知道,我读过的所有内容都告诉我这是非常基本的!)代码的编辑片断,我写:

Imports System.Data.OleDb 
Imports System.Windows.Forms 
Imports Excel = Microsoft.Office.Interop.Excel 

Class MainWindow 

    Private Sub Button1_Click(ByVal sender As System.Object, _ 
ByVal e As System.EventArgs) Handles edit.Click 

    ... 

    Dim newButton As New Button 
    newButton.Text = "New Button" 
    newButton.Top = 200 
    newButton.Left = 20 
    Me.Controls.Add(newButton) 

    ... 

    End Sub 

我的眼睛,这看起来非常简单,正确的,但我得到一个错误:

“‘控制’是不是成员'myApp.MainWindow'。”

以前有没有人遇到过这个问题,或者知道问题是什么?道歉,如果这确实是一个简单的修复:)

回答

0

well MainWindow不是表格。创建一个新的项目,并将相同的代码复制到一个可以工作的按钮中。

你必须找出你的表单控制有什么问题。

5

您收到的错误是告诉您ControlsMainWindow内不存在。基本上,这个名称没有属性可以从你的事件处理程序访问。如果您正在使用WPF并且MainWindow继承Window,那么您需要在Content属性中设置某些内容。

这样做的最好方法是将某种形式的容器控制作为窗口的内容。你可以在XAML或代码中定义这个(通过代码你应该设置Window.Content属性)。然后,您可以将更多控件添加到该容器。建议容器GridCanvasStackPanel

我建议是这样的:

XAML

<MainWindow ...> 

    <StackPanel x:Name="ControlContainer"> 
     <Button Content="Click me to create buttons!" Click="CreateButton_Click" /> 
    </StackPanel> 
</MainWindow> 

代码隐藏

Private Sub CreateButton_Click(ByVal sender As Object, ByVal e As EventArgs) 

    Dim button As New Button() 

    ' Initialize the button 
    ' ... 

    ' Add the button to the stack panel 
    Me.ControlContainer.Children.Add(button) 
End Sub 
0

它看起来像你是mixi ng WinForms和WPF编码 - 这是两种不同的技术。

This link可以帮助你在运行时WPF

添加一个按钮