Visual Studio WPF 如何在 TextBox 中写入内容时立即更改标签中的文本

Visual Studio WPF How to make text ina a label instantly change when writing something in a TextBox

所以我有一个文本框和一个标签。 如果我在文本框中写了一些东西,我希望标签能够显示我当前在文本框中写的文本。

<Window x:Class="WhosebugWPF.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:WhosebugWPF"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <Label Margin="15" x:Name="lbl"></Label>
    <TextBox Width="220" Height="40" VerticalContentAlignment="Center" FontSize="14" x:Name="txtBox" 
             Text="{Binding ElementName=lbl, Path=Content, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
</Window>

如果你不想将数据存储在代码后面或其他东西中,就这么简单。

把标签的Content属性绑定到文本框的Text属性就好了这:Content="{Binding ElementName=TextBox1, Path=Text}"

检查下面的示例代码!

<Window x:Class="TestApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

        <TextBox x:Name="TextBox1" HorizontalAlignment="Left" Height="23" Margin="203,109,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label Content="{Binding ElementName=TextBox1, Path=Text}" HorizontalAlignment="Left" Margin="203,172,0,0" VerticalAlignment="Top" Width="120" />

    </Grid>
</Window>

如果要保存数据,则将内容和文本 属性 绑定到单个 属性 并启用 TwoWay绑定。