views:

115

answers:

3

Hi,

I want to display a child window that contains a combobox with several values coming from one of the child window's property:

public partial class MyChildWindow : ChildWindow
{
    private ObservableCollection<MyClass> _collectionToBind = // initialize and add items to collection to make sure it s not empty...

    public ObservableCollection<MyClass> CollectionToBind
    {
        get { return _collectionToBind; }
        set { _collectionToBind = value; }
    }
}

How do I bind in XAML my combobox to the ComboBoxContent collection (both are in the same class)? I've tried several things such as:

 <ComboBox x:Name="linkCombo" ItemsSource="{Binding Path=CollectionToBind }" DisplayMemberPath="Description">

I've only been able to bind it in the code behind file and would like to learn the XAML way to do it.

Thank you!

A: 

You need to set the DataContext of the ChildWindow to what contains the values you'd like to bind to. In this case where you're putting the values you want to bind to on the ChildWindow itself so just put a line in the constructor assigned the DataContext to itself.

DataContext = this;
David Padbury
A: 

In this case I would use ElementToElement binding like this:-

 <ComboBox x:Name="linkCombo" ItemsSource="{Binding Path=Parent.CollectionToBind, ElementName=LayoutRoot }" DisplayMemberPath="Description">

You give the Content element of the ChildWindow the x:Name of LayoutRoot (in the standard template for child window this is done for you). Hence you can bind to this named element and navigate to the containing ChildWindow by using its Parent property.

Using DataContext = this is tempting and works in simple scenarios but things can get awkward in more complex requirements when the DataContext has already been taken in this way.

AnthonyWJones
Thanks! Works like a charm!
AlexB
A: 

You can also do this using a RelativeSource binding in the XAML, like this:

{Binding Path=CollectionToBind, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}

However, a better way to do this would be to put the CollectionToBind in a separate class and assign it to the Window DataContext. Now both the Window and the XAML Bindings can all refer to the same class as the DataContext and you can isolate more of your logic into this class rather than putting it in the Window implementation.

Dan Bryant
I believe that FindAncestor is WPF only, not Silverlight.
David Padbury
D'oh! I'm always missing the Silverlight tag.
Dan Bryant