Interacting with Code-Behind
In the following example, we will allow the user to change the message Hello World! to one of their choice. Starting from the previous example, we will follow the given steps:
- Open the
mainpage.xaml
file. - Replace the XAML code inserted in the previous example by the one highlighted as follows (we have added an additional textbox, a button, and identifiers for the controls).
<Grid x:Name="LayoutRoot" Background="White"> <StackPanel Orientation="Vertical"> <TextBlock x:Name="tbLabel" Text="Hello World!" FontSize="20"/> <StackPanel Orientation="Horizontal"> <TextBlock Text="New Text:" FontSize="16"/> <TextBox x:Name="txInput" Width="120"/> <Button Content="Change"/> </StackPanel> </StackPanel> </Grid>
- When we build and execute the project, we realize that our window now has the aspect as shown in the following screenshot:
- Next, we must implement the response to the
Click
event of the Change button. - Hook to the
Click
event directly in the XAML file. As soon as we start typing, IntelliSense (Microsoft's implementation of autocompletion) will ask us if we want to create the method (hitting Enter or Tab would create the method with the default name or with the name of the control after selecting aClick
event). - Execute the same operation from the Properties panel (or by directly double-clicking on the button control):
- As a result, XAML will look as follows:
<Button Content="Change" Click="Button_Click"/>
- In Code-Behind, in the method invoked by the
Click
event, we must add a line of code, which transfers the text content entered by the user to the tag where we showed 'Hello World'.private void Button_Click(object sender, RoutedEventArgs e) { tbLabel.Text = txInput.Text; }
- When we execute, we will be able to enter a new text that substitutes 'Hello World'.
推薦閱讀
- 數據庫應用實戰
- 數據庫原理及應用教程(第4版)(微課版)
- 劍破冰山:Oracle開發藝術
- SQL Server 2012數據庫技術與應用(微課版)
- 數據之巔:數據的本質與未來
- 數據要素五論:信息、權屬、價值、安全、交易
- Creating Dynamic UIs with Android Fragments(Second Edition)
- 3D計算機視覺:原理、算法及應用
- 數字媒體交互設計(初級):Web產品交互設計方法與案例
- 視覺大數據智能分析算法實戰
- Hadoop集群與安全
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- SQL Server深入詳解
- 深入理解InfluxDB:時序數據庫詳解與實踐
- 大數據技術原理與應用:概念、存儲、處理、分析與應用