我有兩個文本框,我想保持同步,即兩個文本框的內容應該完全相同。如果一個文本框更改其他文本框內容應自動同步,反之亦然。我想用WPF數據綁定工具來實現它。我有以下代碼:保持兩個文本框在WPF中同步
<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上指定綁定:
<TextBox x:Name="firstTextBox" Background="Silver" Text="{Binding Source=secondTextBox, Path=Text, Mode=TwoWay}"></TextBox>
此外,沒有運行時錯誤。我究竟做錯了什麼?
正是我想要的。唯一的區別是,我使用Source = secondTextBox,並且在您的代碼中它是ElementName = secondTextBox。你能否解釋一下這個區別?我將你的回答標記爲答案;它解決了我的問題。 – 2011-05-09 05:14:42
@Anand Patel:查看'ElementName'的文檔。這些評論描述了它,它有一個與你的相似的例子。還有一個鏈接到綁定概述,這是很好的閱讀。這裏是鏈接:http://msdn.microsoft.com/en-us/library/system.windows.data.binding.elementname.aspx – 2011-05-09 05:36:08