2010-10-21 65 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}" /> 
相关问题