[英]For a user control, how to set the binding of a item template item to a user property?
我有一個簡單的用戶控件,它實際上只是一個帶有一些自定義邏輯的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的任何類型的自定義集合(人,汽車等)顯示的屬性名稱。
我認為我無法以編程方式修改datatemplate。 有什么辦法可以通過綁定(相對源)做到這一點?
我不確定這是否可行,但是我認為您可以將文本直接綁定到ValueMemberBinding屬性,並使用轉換器從中獲取文本。
<TextBlock Text="{TemplateBinding DisplayMember}" />
感謝您的建議。
我無法獲得我偏愛的解決方案,但是我的解決方法是僅將datatemplate資源作為屬性傳遞,並將其分配給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}" />
這不是最好的方法,但現在可以使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.