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; 
    } 
相關問題