WPF之Binding的使用(二)

一、  前言

初学WPF经常被Binding搞得苦不堪言,Binding的重用性就不做介绍了,在WPF应用程序开发中Binding是一个非常重要的部分。WPF也是近期才接触,学习WPF也是在网上查资料与微软的MSDN进行学习,写本博客的目为了温故而知新把学习过程记录下来,以备后查。

二、  WPFBinding

接下还是用做几个示例来做演示如果通过绑定把ListBox中选中的值显示到TextBlock中

1.)首先,给ListBox添加ListBoxItem,做为ListBox的选项 。

2.)其次,把TextBlock 的 Text通过 Binding 与 ListBox 选择项进行绑定。Binding 语法中的 ElementName 属性指示 TextBlock 的 Text 属性要与其绑定的控件的名称。Path 属性指示我们将绑定到Text属性上ListBox元素的属性。如下代码所示

 1 <Window x:Class="Student.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:Student"
 7         mc:Ignorable="d"
 8         Title="MainWindow" Height="650" Width="800">
 9     <Grid>
10 
11         <Grid.RowDefinitions>
12             <RowDefinition Height="200"/>
13             <RowDefinition Height="200"/>
14             <RowDefinition Height="*"/>
15         </Grid.RowDefinitions>
16 
17         <StackPanel Grid.Row="0">
18             <TextBlock Width="250" Height="26" Text="湖南旅游景点:" TextWrapping="Wrap" Background="Azure" FontSize="20"/>
19             <ListBox x:Name="listStockName" Width="248" Height="90" Background="Azure" FontSize="20">
20                 <ListBoxItem Content="武陵源"/>
21                 <ListBoxItem Content="南岳衡山 "/>
22                 <ListBoxItem Content="岳阳楼"/>
23                 <ListBoxItem Content="岳麓书院 "/>
24                 <ListBoxItem Content="君山岛 "/>
25                 <ListBoxItem Content="张家界"/>
26                 <ListBoxItem Content="花明楼 "/>
27                 <ListBoxItem Content="崀山风景名胜区"/>
28                 <ListBoxItem Content="凤凰古城"/>
29             </ListBox>
30             <TextBlock Width="250" Height="24" Text="你所选中的景点:" Background="Aqua" FontSize="20" />
31             <TextBlock Width="250" Height="30" Text="{Binding ElementName=listStockName, Path=SelectedItem.Content}" Background="Azure" FontSize="26"/>
32         </StackPanel>
33 
34     </Grid>
35 
36 </Window>
View Code

相关文章:

  • 2021-08-07
  • 2022-12-23
  • 2022-01-31
  • 2021-06-05
猜你喜欢
  • 2021-08-22
  • 2022-01-07
  • 2021-11-12
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案