在雙向綁定中,使用者可以通過使用者界面修改資料,并在源中更新資料。如果在使用者檢視視圖時更改源,則需要更新視圖。
讓我們看看下面的示例,其中一個組合框具有三個組合框項目和一個文本框,并建立了一些屬性。在此示例中,我們沒有任何标準資料源,但UI元素綁定到其他UI元素。
XAML代碼:
<Window x:Class="點選事件.雙向綁定資料"
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:點選事件"
mc:Ignorable="d"
Title="雙向綁定資料" Height="450" Width="800">
<!--棧面闆-->
<StackPanel>
<!--下拉框-->
<ComboBox Name = "comboBox" Margin = "50" Width = "100">
<ComboBoxItem Content = "Green" />
<ComboBoxItem Content = "Yellow" IsSelected = "True" />
<ComboBoxItem Content = "Orange" />
</ComboBox>
<TextBox Name = "textBox" Margin = "50"
Width = "100" Height = "23" VerticalAlignment = "Top"
Text = "{Binding ElementName = comboBox, Path = SelectedItem.Content,
Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}"
Background = "{Binding ElementName = comboBox, Path = SelectedItem.Content}">
</TextBox>
</StackPanel>
</Window>
編譯并執行上面的代碼時,它将産生以下輸出。當使用者從組合框中選擇項目時,文本框文本和背景顔色将相應地更新。
同樣,當使用者在文本框中鍵入有效的顔色名稱時,組合框和文本框背景顔色也将更新。