[英]WPF TargetInvocationException when trying to change textbox text in SelectionChanged method
So my code gives me a TargetInvocationException 所以我的代码给了我TargetInvocationException
link to screenshot of exception details 链接到异常详细信息的屏幕截图
This is my code 这是我的代码
public partial class MainWindow
{
Double totalPrice = 0;
public MainWindow()
{
InitializeComponent();
}
private void txtDiscount_SelectionChanged(object sender, RoutedEventArgs e)
{
Double newTotalPrice = 0;
if (!String.IsNullOrEmpty(txtDiscount.Text))
{
newTotalPrice = totalPrice - Double.Parse(txtDiscount.Text);
}
txtFullAmount.Text = newTotalPrice.ToString();
}
The last line is the one thats making it crash, Im trying to assign a textbox to change whenever a different textbox changes. 最后一行是导致崩溃的那行,我试图分配一个文本框,以便每当一个不同的文本框发生更改时就进行更改。
The funny part is that this works perfectly if I change the title instead 有趣的是,如果我改为标题,这将非常有效
this.Title = newTotalPrice.ToString();
Edit: Also my original code works if used with a button instead. 编辑:同样,如果与按钮一起使用,我的原始代码也可以使用。
Edit <TextBox Background="#ecf0f1" IsReadOnly="True" Text="" Name="txtFullAmount" SelectionChanged="txtDiscount_SelectionChanged" HorizontalAlignment="Left" Height="23" Margin="505,511,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="85"/>
编辑
<TextBox Background="#ecf0f1" IsReadOnly="True" Text="" Name="txtFullAmount" SelectionChanged="txtDiscount_SelectionChanged" HorizontalAlignment="Left" Height="23" Margin="505,511,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="85"/>
I think you set a SelectedIndex
in your XAML. 我认为您在XAML中设置了
SelectedIndex
。 In this case, the SelectionChanged
event is raised before the window is completly initialized. 在这种情况下,在完全初始化窗口之前引发
SelectionChanged
事件。 Before the initialisation, the member variables for the controls are always null
. 在初始化之前,控件的成员变量始终为
null
。
The easiest way is to check if the TextBox exists and return if it is null
: 最简单的方法是检查TextBox是否存在并返回
null
:
private void txtDiscount_SelectionChanged(object sender, RoutedEventArgs e)
{
if(txtFullAmount == null) return;
//your code
}
The assignment to the Title
works, because this
exists already at this moment. 分配给
Title
的作品,因为this
在这一刻已经存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.