Silverlight 数据绑定 (1):怎样实现数据绑定
一个数据绑定可以通过 Binding 对象来描述,其中包含数据源,要绑定的属性路径(Path),目标,目标属性等。
其中目标属性必须是依赖属性(DependencyProperty)。
为了说明方便,首先定义一个数据类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Person { public int Age { get; set; } public string Name { get; set; } } 例子1: < ListBox x:Name="list1"> </ ListBox > public partial class Page : UserControl { public Page() { InitializeComponent(); var persons = new List< Person >(); for(var i=0; i< 5 ; i++) { persons.Add(new Person {Name = "Person " + i.ToString(), Age = 20 + i}); } list1.DataContext = persons; } } 这里仅指定了 list1 的 DataContext 属性,运行后发现页面没有显示。 如果在页面里改一改: <ListBox x:Name="list1" ItemsSource="{Binding}"> </ ListBox > |
会发现绑定成功。但是数据项显示为默认的 Person 对象 ToString() 后的表示,不太友好。如下图:
或者,也可以将后台代码改成:
1 | list1.ItemsSource = persons; |
而页面 markup 仍然是:
1 2 3 | < ListBox x:Name="list1"> </ ListBox > |
这样也能绑定成功。
这里的原因在于:ListBox 通过 ItemsSource 里的数据去填充数据项,所以直接给这个属性赋值是可以的。
或者,通过空绑定语法 {Binding},指定 ItemsSource 属性绑定为数据源的对象本身(未指定绑定路径)。而数据源就是通过 DataContext 获得的,并且这个属性的数据可以从父对象继承下来。
下面给 ListBox 指定列表项的数据模板,让它显示的好看一点:
1 2 3 4 5 6 7 8 9 10 | < ListBox x:Name="list1"> < ListBox.ItemTemplate > < DataTemplate > < StackPanel Orientation="Horizontal"> < TextBlock Text="{Binding Age}" Margin="20,0" /> < TextBlock Text="{Binding Name}" /> </ StackPanel > </ DataTemplate > </ ListBox.ItemTemplate > </ ListBox > |
显示如下:
还可以将 DataTemplate 定义到 App 的 Resource 里去,以便于重用。
App.xaml:
1 2 3 4 5 6 7 8 9 10 11 12 13 | < Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SilverlightTestApp.App" > < Application.Resources > < DataTemplate x:Key="ListBoxDataTemplate"> < StackPanel Orientation="Horizontal"> < TextBlock Text="{Binding Age}" Margin="20,0" /> < TextBlock Text="{Binding Name}" /> </ StackPanel > </ DataTemplate > </ Application.Resources > </ Application > |
Page.xaml:
1 2 3 4 5 6 7 8 9 | < UserControl x:Class="SilverlightTestApp.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300"> < Grid x:Name="LayoutRoot" Background="White"> < ListBox x:Name="list1" ItemTemplate="{StaticResource ListBoxDataTemplate}"> </ ListBox > </ Grid > </ UserControl > |
运行后效果一样。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?