我最近從Windows窗體移到了WPF。我從Reed Copsey的系列'Better User and Developer Experiences – From Windows Forms to WPF with MVVM'開始。在4th part of the series,下面的代碼應填寫文本框與數據:我在做什麼錯,所以數據綁定目標不受數據綁定源的影響
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=Feed.Title, Mode=OneWay}" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=Feed.Link.AbsoluteUri, Mode=OneWay}" />
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=Feed.Description, Mode=OneWay}"/>
我試圖用這個模板的代碼爲「更新目標(TextBlock.Text
)作爲源(TextBox.Text
)更新」,那是我的全XAML代碼:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="608.134" Width="768.284">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Height="28" Margin="442,56,0,0" VerticalAlignment="Top" Width="139" Click="Button_Click_1"/>
<TextBox x:Name="TextBox1" HorizontalAlignment="Left" Height="28" Margin="56,56,0,0" TextWrapping="Wrap" Text="TextBox1" VerticalAlignment="Top" Width="237"/>
<TextBlock HorizontalAlignment="Left" Height="66" Margin="56,168,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="285"
Text="{Binding Path=TextBox1.Text, Mode = OneWay}"/>
</Grid>
</Window>
爲TextBlock
的文本的期望值爲"TextBox1"
(TextBox1.Text
),但TextBlock
文字竟是空!
因此,我檢查了what triggers source updates,並決定將綁定模式更改爲TwoWay
,但我得到了相同的結果!
最後,我發現"How to: Control When the TextBox Text Updates the Source"顯示如何做到這一點。根據什麼Reed Copsey在他的系列的這一部分中說:
代碼少意味着少維護,少測試,少擔心。
,並根據上MSDN找到源:
<Label>Enter a Name:</Label>
<TextBox>
<TextBox.Text>
<Binding Source="{StaticResource myDataSource}" Path="Name"
UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
<Label>The name you entered:</Label>
<TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=Name}"/>
我將打字(大致)相同的代碼量。這樣的任務(通過TextBox更改來更改TextBlock)可以使用常規事件處理程序完成。所以我的問題是:
- 如果使用大致相同數量的代碼可以完成相同的任務,是什麼使得WPF數據綁定如此特殊?
- 我的第一個代碼出了什麼問題?
- 在上面的MSDN代碼中,他們必須鍵入源和目標的XAML代碼。如果我希望源代碼在課堂內成爲價值,是否有可能完成這樣的使命?如何?
任何幫助將不勝感激, 在此先感謝。
簡潔地說,謝謝! –