views:

52

answers:

3

I have a simple user control, which is essentially just an AutoCompleteBox with some custom logic.

For a specific instance (a collection of Persons), I want it to look like this:

<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>

However, I want to make the data source generic and therefore the display values will be different (ValueMemberBinding and the template TextBlock text). That is why I am making a custom control so I can specify the differences with properties.

I have no problem setting the source with a user control property, but I am having difficulty with the display binding properties. Right now I have:

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?
    }
}

I want the DisplayMember property to be the property name to display for whatever kind of custom collection (persons, cars, etc) I have bound to the AutoCompleteBox.

I don't think I can modify the datatemplate programmatically. Is there a way I can do this with binding (relative source)?

+2  A: 

I am not sure if this works, but I think you could bind the text directly to the ValueMemberBinding property and use a converter to get the text out of it...

Gustavo Cavalcanti
A: 
<TextBlock Text="{TemplateBinding DisplayMember}" />
NVM
A: 

Thank you for the suggestions.

I was unable to get a solution that I preferred, but my workaround is to just pass in a datatemplate resource as a property and that gets assigned to the autocompletebox itemtemplate.

Define a template:

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

Create the user control property for it:

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

Now:

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

Not the best method, but it will work for now.

AdamD