3

我得到这个未处理的异常错误:TargetInvocationException发生,但我完全不知道为什么

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll.

Additional information: Exception has been thrown by the target of an invocation.

这是我的代码的短。它是两个文本框的计算器,当用户按下WPF中的+, - ,/,x按钮时,它们应该一起成为新的答案。

public partial class MainWindow : Window 
{ 
    public string numberInString 
    { 
     get { return TextDoos.Text; } 
     set { TextDoos.Text = value; } 
    } 

    public MainWindow() 
    { 
     if(TextDoos.Text == "") 
     { 
      if(TextDoos2.Text == "") 
      { 
       RekenFunctie(TextDoos.Text, TextDoos2.Text); 
      } 
     } 
    } 
} 

public int RekenFunctie(string numberInString, string numberInString) 
{ 
    int antwoord; 
    int getal = Convert.ToInt32(numberInString); 
    int getal2 = Convert.ToInt32(numberInString2); 

    if (Buttons.IsPressed) // This is the + button, there are also -,x,/ buttons. 
    { 
     antwoord = getal + getal2; 
     return antwoord; 
    } 
} 

我不明白为什么它不工作...

+3

TargetInvocationException总是有一个InnerException - 你应该看看那个以找出原因。 –

回答

3

你错过的InitializeComponent()MainWindow构造函数的调用;

public MainWindow() 
{ 
    InitializeComponent(); 
    button1.Click += button1_click; //'+' button 
} 

private void button1_click(object sender, RoutedEventArgs e) 
{ 
    int antwoord; 
    int getal = Convert.ToInt32(TextDoos.Text); 
    int getal2 = Convert.ToInt32(TextDoos2.Text); 

    antwoord = getal + getal2; 
    resultTextBox.Text = antwoord ; 
} 

无论如何,你的代码很奇怪。 RekenFunctie进行了一些计算,但您从构造函数中调用它。所以,你只运行一次该代码,但我认为你的用户想要与你的计算器进行交互。

我想你应该读些关于Button.Click事件的东西。

+1

谢谢你,我应该删除这个问题吗? –

+1

不,这个问题和答案可能会导致有人遇到类似的问题。 –

+0

但是我不能在像Buttons_Clicked()这样基于事件的方法中执行RekenFunctie(),因为它给了我另一个错误,这就是为什么我这样说......我仍然没有得到所有的限制/ C#的构造函数,事件和其他东西的规则。 –

0

我有类似的问题。

从TextBox的属性更改evet设置TextBlock上的文本时,出现同样的错误。

private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     MainTextBlock.Text = ((TextBox)sender).Text; 
    } 

我认为这是被称为在运行时前MainTextBlock组件被初始化。

在我的情况,只是检查null做了伎俩。

private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     if (MainTextBlock != null) 
      MainTextBlock.Text = ((TextBox)sender).Text; 
    } 
相关问题