2010-10-21 31 views
4

我有一個簡單的用戶控件,它基本上只是一個自定義邏輯的AutoCompleteBox。對於用戶控件,如何設置項目模板項目與用戶屬性的綁定?

對於特定實例(人的集合),我希望它看起來像這樣:

<sdk:AutoCompleteBox Name="myACB" ItemsSource="{Binding People}" FilterMode="StartsWith" MinimumPrefixLength="2" ValueMemberBinding={Binding LastName}> 
    <sdk:AutoCompleteBox.ItemTemplate> 
    <DataTemplate> 
     <TextBlock Text="{Binding LastName}" /> 
    </DataTemplate> 
    </sdk:AutoCompleteBox.ItemTemplate> 
</sdk:AutoCompleteBox> 

不過,我想使數據源通用的,因此顯示的值會有所不同(ValueMemberBinding和模板TextBlock文本)。這就是爲什麼我正在製作自定義控件,以便我可以指定與屬性的差異。

我沒有問題,用一個用戶控件屬性設置源,但我有顯示綁定屬性的困難。現在,我有:

public static DependencyProperty DisplayMemberProperty = DependencyProperty.Register("DisplayMember", typeof(string), typeof(myAutoComplete), null); 

public string DisplayMember 
{ 
    get 
    { return myACB.ValueMemberPath; } 
    set 
    { 
     myACB.ValueMemberPath = value; // this works fine 
     // but how can set the text binding for the templated textblock? 
    } 
} 

我想DisplayMember屬性是屬性名稱顯示任何類型的自定義集合(人,汽車等)的我已綁定到AutoCompleteBox。

我不認爲我可以通過編程修改數據模板。有沒有一種方法,我可以做到這一點與綁定(相對來源)?

回答

0

謝謝你的建議。

我無法獲得我首選的解決方案,但我的解決方法是隻傳入數據模板資源作爲屬性,並將其分配給autocompletebox itemtemplate。

定義模板:

<DataTemplate x:Key="myCustomDT"> 
    <!-- whatever you want here --> 
</DataTemplate> 

爲它創建的用戶控件屬性:

public static DependencyProperty DisplayTemplateProperty = DependencyProperty.Register("DisplayTemplate", typeof(DataTemplate), typeof(myAutoComplete), null); 
public DataTemplate DisplayTemplate { 
    get { return myACB.ItemTemplate; } 
    set { myACB.ItemTemplate = value; } 
} 

現在:

<local:myAutoComplete DisplayTemplate="{StaticResource myCustomDT}" /> 

不是最好的方法,但它會爲現在的工作。

2

我不知道,如果這個工程,但我認爲你可以在文本直接綁定到ValueMemberBinding屬性,並使用一個轉換器來獲取文本出來吧......

0
<TextBlock Text="{TemplateBinding DisplayMember}" /> 
相關問題