请WPF同步两个文本框 [英] Keep two textboxes synchronized in WPF

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

问题描述

我有我要保持同步的两个文本框即两个文本框的内容应该是完全一样的。如果一个TextBox改变其他文本框的内容应自动,反之亦然同步。我想用WPF数据绑定设施来实现它。我有以下的code:

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:

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天全站免登陆