WPF技巧(1)异步绑定
2010-04-26 22:10 Clingingboy 阅读(4239) 评论(0) 编辑 收藏 举报与大家共勉
当属性值填充好后,与该属性绑定的界面才会开始加载(属性绑定优于控件加载)
这个技巧很简单,但却影响着运行的速度.以下为测试
1.定义一个集合属性
private IList<string> _list; public IList<string> List { get { if (_list == null) { _list = new List<string>(); for (int i = 0; i < 100; i++) { _list.Add("item" + i); } } return _list; } }
2.绑定属性
<Window x:Class="WpfRecipe1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfRecipe1" Title="MainWindow" Height="350" Width="525"> <Grid> <ListBox ItemsSource="{Binding List,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:MainWindow}}}" Height="179" HorizontalAlignment="Left" Margin="76,31,0,0" Name="listBox1" VerticalAlignment="Top" Width="135" /> </Grid> </Window>
上面的代码可以很好的运行.
事实上我们取数据都没这么简单,假设这段数据是从数据里取的,花费3秒时间,我们以线程模拟
private IList<string> _list; public IList<string> List { get { System.Threading.Thread.Sleep(3000); //省略代码
return _list; } }
下面重新运行代码,你将会发现程序会先停滞三秒.结论在刚开始已经提到
即使下面的代码也是遵循上面的原则
<TabControl> <TabItem Header="tab1"></TabItem> <TabItem Header="tab2"> <ListBox ItemsSource="{Binding List,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:MainWindow}}}" Height="179" HorizontalAlignment="Left" Margin="76,31,0,0" Name="listBox1" VerticalAlignment="Top" Width="135" /> </TabItem> </TabControl>
这是相当郁闷的一段代码,因为用户什么也没看到,却让用户等了三分钟.
首先想到的是自己异步取数据,其实还有一个更简单的方法就是在绑定时将IsAsync设置为True
<ListBox ItemsSource="{Binding List, IsAsync=True, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:MainWindow}}}" Height="179" HorizontalAlignment="Left" Margin="76,31,0,0" Name="listBox1" VerticalAlignment="Top" Width="135" />
说实话我也刚刚知道有这么一个属性,这个属性几乎被我们忽略,平时用到很少,因为我们第一思维就是自己异步去加载数据,学了一招
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2006-04-26 SqlDataSource抓图