我试图举一个例子来说明这本书

private Button button1;
public MainWindow()
{
    InitializeComponent();
}
private void InitializeComponent()
{
    // Configure the form.
    this.Width = this.Height = 285;
    this.Left = this.Top = 100;
    this.Title = "Code-Only Window";
    // Create a container to hold a button.
    DockPanel panel = new DockPanel();
    // Create the button.
    button1 = new Button();
    button1.Content = "Please click me.";
    button1.Margin = new Thickness(30);
    // Attach the event handler.
    button1.Click += button1_Click;
    // Place the button in the panel.
    IAddChild container = panel;
    container.AddChild(button1);
    // Place the panel in the form.
    container = this;
    container.AddChild(panel);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    button1.Content = "Thank you.";
}


但这给了我一个错误:

"Type 'WpfApplication1.MainWindow' already defines a member called 'InitializeComponent' with the same parameter types"

最佳答案

在Visual Studio中创建的WPF Window类通常具有InitializeComponent方法,该方法用于初始化其属性和内容-What does InitializeComponent() do, and how does it work in WPF?

它是从XAML标记生成的,并且不包含在代码隐藏的.cs文件中,但是对于the compiler(and msbuild.exe)来说,它仍然是Window类的有效内在部分-如果创建新的空Window并单击InitializeComponent()调用然后将打开一个带有初始化代码的*.g.i.cs临时文件。

因此,当您将另一个InitializeComponent方法放入文件后面的代码中时,将导致方法定义不明确。



解:

将您的自定义方法重命名为InitializeComponentsCustom并在构造函数中调用它:

public MainWindow()
{
    InitializeComponent();

    InitializeComponentsCustom();
}

private void InitializeComponentsCustom()
{
    // ...
}


或者只是将book方法中的整个代码放入构造函数中(只是不要删除原始的InitializeComponent调用)。

关于c# - 错误-已经使用相同的参数类型定义了一个名为'InitializeComponent'的成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25428175/

10-11 17:39