WPF中的文本框文本更改事件 [英] Text Box Text Changed event in WPF

查看:669
本文介绍了WPF中的文本框文本更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我在WFA中有2个文本框.以下代码有效.

So, for example if I have 2 text boxes in WFA. The following code works.

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        textBox2.Text = textBox1.Text;
    }

我明白了.当我更改它时,第二个文本框中的文本等于第一个文本中的文本.

And I get this. The text in the second text box equals to the text in the first one, when I change it.

但是当谈到WPF时,我得到了完全不同的行为.当我这样做时.

But when it comes to WPF, I get a completely different behavior. When I do this.

private void textBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        textBox1.Text = textBox.Text;
    }

然后按Ctrl + F5组合键测试该应用程序,什么也没有发生.日志显示"Build Succeeded",什么也没有.怎么了?

And press Ctrl+F5 to test the application, nothing happens. The log says "Build Succeeded" and nothing. What is wrong here?

这是XAML代码.

    <Window x:Class="TextBoxTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TextBoxTest"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="212,77,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" TextChanged="textBox_TextChanged"/>
    <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="212,124,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>

</Grid>

推荐答案

您遇到了空引用异常.创建textBox控件时,它将触发textBox1上的textChange事件,到那时,尚未创建textBox1,因此为null.您只需在XAML中更改文本框的顺序,就可以了. 但是有一种更好的方法,直接在具有绑定的XAML中进行:

You are encountering a null reference exception. When the textBox control is created it will trigger the textChange event on textBox1 and by that point, textBox1 isn't created and is therefore null. You can just change the order of the textboxes in the XAML and you will be fine. But there is a nicer way of doing this, directly in XAML with Binding:

<TextBox x:Name="textBox" />
<TextBox x:Name="textBox1" Text="{Binding ElementName=textBox, Path=Text}" />

(我排除了一些属性以使示例更简洁) 根据您希望另一个文本框更新的时间,可以将UpdateSourceTrigger添加到绑定中:

(I excluded some attributes to make the example more clean) Depending on WHEN you want the other textbox to update you can add UpdateSourceTrigger to the binding:

Text="{Binding ElementName=textBox, Path=Text, UpdateSourceTrigger=PropertyChanged}"

这篇关于WPF中的文本框文本更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆