官术网_书友最值得收藏!

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:

  1. Open the mainpage.xaml file.
  2. 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>
  3. When we build and execute the project, we realize that our window now has the aspect as shown in the following screenshot:
    Interacting with Code-Behind
  4. Next, we must implement the response to the Click event of the Change button.
  5. 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 a Click event).
    Interacting with Code-Behind
  6. Execute the same operation from the Properties panel (or by directly double-clicking on the button control):
    Interacting with Code-Behind
  7. As a result, XAML will look as follows:
    <Button Content="Change" Click="Button_Click"/>
  8. 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;
    }
  9. When we execute, we will be able to enter a new text that substitutes 'Hello World'.
    Interacting with Code-Behind
主站蜘蛛池模板: 临西县| 丹凤县| 临西县| 宣武区| 西昌市| 安康市| 甘孜县| 孟连| 阳江市| 临沧市| 抚宁县| 全州县| 邯郸县| 浮山县| 长宁区| 西华县| 合水县| 石嘴山市| 东乌珠穆沁旗| 蓬莱市| 洛川县| 洛南县| 黑河市| 彭水| 肇源县| 环江| 天全县| 福海县| 教育| 盘山县| 大理市| 旬邑县| 黄浦区| 北安市| 叶城县| 谢通门县| 瓮安县| 大丰市| 沙河市| 玉林市| 辽宁省|