在 WPF 中保持两个文本框同步 [英] Keep two textboxes synchronized in WPF

查看:31
本文介绍了在 WPF 中保持两个文本框同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要保持同步的文本框,即两个文本框的内容应该完全相同.如果一个文本框更改其他文本框内容应自动同步,反之亦然.我想使用 WPF 数据绑定工具来实现它.我有以下代码:

I have two textboxes which I want to keep synchronized i.e. the content of both the textboxes should be exactly same. If one textbox changes the other textbox content should be synchronized automatically and viceversa. I want to achieve it using WPF databinding facilities. I have the following code:

<Window x:Class="WPFLearning.DataBindingTwoWay"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataBindingTwoWay" Height="300" Width="300">
    <Grid>
        <StackPanel>
            <TextBox x:Name="firstTextBox" Background="Silver"></TextBox>
            <TextBox x:Name="secondTextBox" Background="Gold" ></TextBox>
        </StackPanel>
    </Grid>
</Window>

我尝试使用绑定标记扩展,但无法正确使用.这是我在 firstTextBox 上指定 Binding 的方式:

I tried using the Binding Markup Extensions but could not get it right. Here is how I specified Binding on the firstTextBox:

<TextBox x:Name="firstTextBox" Background="Silver" Text="{Binding Source=secondTextBox, Path=Text, Mode=TwoWay}"></TextBox>

此外,没有运行时错误.我究竟做错了什么?

Also, there are no runtime errors. What am I doing wrong?

推荐答案

如果这就是你想做的,WPF 会让你去做:

If that is what you want to do, WPF will let you do it:

<Grid>
    <StackPanel>
        <TextBox x:Name="firstTextBox" Background="Silver" Text="{Binding Path=Text, ElementName=secondTextBox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
        <TextBox x:Name="secondTextBox" Background="Gold" ></TextBox>
    </StackPanel>
</Grid>

ElementName 语法是对绑定到 DataContext 中的属性的基本方法的一个非常强大的补充.许多疯狂的事情成为可能.

The ElementName syntax is a very powerful addition to the basic approach of binding to properties in the DataContext. Many crazy things become possible.

这篇关于在 WPF 中保持两个文本框同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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