代码改变世界

WPF技巧(1)异步绑定

2010-04-26 22:10  Clingingboy  阅读(4226)  评论(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" />

 

说实话我也刚刚知道有这么一个属性,这个属性几乎被我们忽略,平时用到很少,因为我们第一思维就是自己异步去加载数据,学了一招