Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

binding - Keep two textboxes synchronized in 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>

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...