094243D60-1  
首先我們先建立一個實體類並創建它的集合用於繫結控制項的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">
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()