您的位置:首页 > 其它

Silverlight中使用MVVM(6):AutoComplteBox的异步过滤

2011-03-30 10:41 330 查看
Silverlight中使用MVVM(1)--基础 Silverlight中使用MVVM(2)—提高 Silverlight中使用MVVM(3)—进阶 Silverlight中使用MVVM(4)—演练 Silverlight中使用MVVM(5)-Command II

Toolkit中AutoCompleteBox控件的功能非常强大,其用法可以参考AutoCompleteBox的基本使用这篇文章。

在实际的开发中,数据一般通过WCF异步传递的,要实现AutoCompleteBox的过滤数据,主要用到的是Populating事件和PopulateComplete方法

[code]      private void autoCompleteBox1_Populating(object sender, PopulatingEventArgs e)
{
ServiceAPI.FilterServiceClient filterServiceClient = new FilterServiceClient();
filterServiceClient.DoWorkCompleted += (obj, arg) =>
                       {
this.autoCompleteBox1.ItemsSource = arg.Result;
this.autoCompleteBox1.PopulateComplete();
};
filterServiceClient.DoWorkAsync();
}
[/code]
上面的代码是比较常见的操作方式,这里我们关注一下如何使用MVVM的方式将其分离到ViewModel中

首先定义名为FilterAsyncParameters的类,其有2个属性,FilterCriteria表示过滤参数,即文本框中的值,FilterComplete 则封装了下PopulateComplete方法
[code]      public class FilterAsyncBehavior : Behavior<AutoCompleteBox>
{
public ICommand FilterAsyncCommand
{
get
  {
return (ICommand)GetValue(FilterAsyncCommandProperty);
  }
set
  {
SetValue(FilterAsyncCommandProperty, value);
  }
}
public static readonly DependencyProperty FilterAsyncCommandProperty = DependencyProperty.Register("FilterAsyncCommand",
typeof(ICommand),
typeof(FilterAsyncBehavior),
new PropertyMetadata(null));
...
}
[/code]

这里定义的FilterAsyncCommand用于执行ViewModel里面的ICommand,FilterAsyncBehavior重写了OnAttached,OnDetaching方法

protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Populating += AssociatedObject_Populating;
}

protected override void OnDetaching()
{
AssociatedObject.Populating -= AssociatedObject_Populating;
base.OnDetaching();
}

private void AssociatedObject_Populating(object sender, PopulatingEventArgs e)
{
ICommand filterCommand = FilterAsyncCommand;

if (filterCommand != null)
{
//创建过滤参数
var parameters = new FilterAsyncParameters(AssociatedObject.PopulateComplete, e.Parameter);
filterCommand.Execute(parameters);
e.Cancel = true;
}
}

[/code]
ViewModel中定义了ICommand属性

public AcbAsyncViewModel()
{

FilterCommand = new RelayCommand<FilterAsyncParameters>(ExecuteFilter);
}
private void ExecuteFilter(FilterAsyncParameters filterAsyncParameters)
{
ServiceAPI.FilterServiceClient filterServiceClient=new FilterServiceClient();
filterServiceClient.DoWorkCompleted += (obj, arg) =>
{
…..

var filter = arg.UserState as FilterAsyncParameters;
filter.FilterComplete();
};
filterServiceClient.DoWorkAsync(filterAsyncParameters);
}

[/code]
View中Xaml代码

<sdk:AutoCompleteBox  ItemsSource="{Binding Data}">
<interactivity:Interaction.Behaviors>
<utilities:FilterAsyncBehavior FilterAsyncCommand="{Binding FilterCommand}" />
</interactivity:Interaction.Behaviors>
</sdk:AutoCompleteBox>

这样就实现了以MVVM实现了AutoCompleteBox的异步过滤数据,实现过程中需要对Behavior等概念有一定理解,希望这篇文章给各位提供一点思路。

代码下载: AutoComplateBoxSamples.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: