轉帖|其它|編輯:郝浩|2011-06-30 14:10:25.000|閱讀 629 次
概述:本文主要介紹如何讓Silverlight AutoCompleteBox控件支持多屬性篩選,希望對大家有幫助。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
首先我們先建立一個實體類并創建它的集合用于綁定控件的ItemSource屬性,這個實體類有兩個屬性,如下:
1: public class AUser
2: {
3: public string Name { set; get; }
4: public string Age { set; get; }
5: }
編寫XAML如下:
<sdk:AutoCompleteBox Height="28" Name="autoCompleteBox1" ValueMemberPath="Age">
<sdk:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Age}"/>
</StackPanel>
</DataTemplate>
</sdk:AutoCompleteBox.ItemTemplate>
</sdk:AutoCompleteBox>
大家都知道, 一般情況下AutoCompleteBox控件只能篩選綁定項中的一個屬性,(及ValueMemberPath在本例中只能設置為Name或Age),并且ValueMemberPath屬性中的路徑既是篩選屬性路徑又是選定項的結果屬性路徑。
接下來我們擴展它,使它能支持多屬性路徑,并能指定輸出結果屬性路徑。我的解決思路是利用附加屬性的力量達到目標,代碼如下:
1: public static class AutoCompleteBoxHelper
2: {
3: private static void OnIsOtherPathChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
4: {
5: var acb = obj as AutoCompleteBox;
6: if (!string.IsNullOrEmpty(e.NewValue.ToString()))
7: {
8: acb.ItemFilter = (s,item)=>{
9: var objType = item.GetType();
10: string path = GetOtherPaths(acb);
11: var pathes = path.Split(',');
12: bool result = false;
13: foreach (string p in pathes)
14: {
15: var propertyInfo = objType.GetProperty(p);
16: string value = propertyInfo.GetValue(item, null).ToString();
17: result |= value.Contains(s);
18: }
19: return result;
20: };
21: }
22: else
23: acb.ItemFilter = null;
24: }
25:
26: public static string GetOtherPaths(DependencyObject obj)
27: {
28: return (string)obj.GetValue(OtherPathsProperty);
29: }
30:
31: public static void SetOtherPaths(DependencyObject obj, string value)
32: {
33: obj.SetValue(OtherPathsProperty, value);
34: }
35:
36: public static readonly DependencyProperty OtherPathsProperty =
37: DependencyProperty.RegisterAttached("OtherPaths", typeof(string),
38: typeof(AutoCompleteBoxHelper),
39: new PropertyMetadata("", OnIsOtherPathChanged));
40: }
OtherPaths屬性就是一個支持多屬性路徑的屬性(如”Name,Age”),并且指定了OtherPaths后ValueMemeberPath的篩選作用就不再工作了,而只保留了選定結果項屬性路徑的功能。
最后要叫它工作:
<sdk:AutoCompleteBox Height="28" Name="autoCompleteBox1" ValueMemberPath="Age"
loc:AutoCompleteBoxHelper.OtherPaths="Age,Name">
運行結果:
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:博客園