views:

56

answers:

2

I have a simple user control which wraps some logic around an AutoCompleteBox. This question could apply to any ItemsControl control like a dropdown or listbox though.

<UserControl>
    <Grid Background="White">
        <sdk:AutoCompleteBox Name="myACB" ItemsSource="{Binding myData}" />
    </Grid>
</UserControl>

I want expose the SelectedItem property of the AutoCompleteBox in a parent where the control is used. My user control is using a view model as its data context though. Otherwise, I think I could just bind the SelectedItem to a dependency property of the user control.

I need to be able to have the parent detect when the child autocompletebox selected item changes. How can I go about this?

+3  A: 

Just create a dependency property in the UserControl and bind it with your internal control like the following:

1) Add a dependency property in the CustomControl:

public System.Collections.IEnumerable ItemsSource
    {
        get { return (System.Collections.IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ItemsSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(System.Collections.IEnumerable), typeof(UserControl1), new UIPropertyMetadata(null));

2) Bind the internal control with the dependency property:

<UserControl ... x:Name="control"     ... >

<ListBox ItemsSource="{Binding ElementName=control, Path=ItemsSource}" />  

Edit: Implement the ItemsSource

Homam
Thank you. This makes sense, but I am unable to get the binding working. I want to get the selected item, so I am binding like SelectedItem="{Binding ElementName=myACB, Path=SelectedItem, Mode=TwoWay}" and I have a dependency property set up in the control class similar like you have shown, but for SelectedItem. I have a break set on the set value but it does not hit the code when I select an item.
AdamD
@Adam: I tested it, and it has worked well, just confirm that the type of SelectedItem is [object], and the default value for dependency property is null. try it again and tell me what happened. Good luck!
Homam
I can get it to work if I don't use a view model as the data context for the control (`this.DataContext = new myControlViewModel();`). Do you have any idea why?
AdamD
+1  A: 

And if you try by this way it could update the property in your user control :

<ListBox SelectedItem="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=OneWayToSource, Path=ThePropertyInMyUserControl}"/>

Then ThePropertyInMyUserControl coulb be an additional dependency property.

Gerrrard