2

I have following XAML (simplified, no ending tags):

<Window Name="myWindow" DataContext="{Binding ElementName=myWindow}" >
    <DockPanel>
        <tb:ToolBar Name="toolbar" DockPanel.Dock="Top">
            <tb:ToolBar.Items>
                <tb:ToolBarControl Priority="-3">
                    <tb:ToolBarControl.Content>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock>Maps:</TextBlock>
                            <ComboBox ItemsSource="{Binding Generator.Maps, ElementName=myWindow}">

But the ComboBox's binding will fail with

Cannot find source for binding with reference 'ElementName=myWindow'

Some facts about the custom controls:

  • tb:ToolBar is UserControl which contains actual ToolBar with ItemsSource bound to the Items property of the tb:ToolBar (of type inheriting IList).

  • The ToolBar's ToolBarItem DataTemplate is chosen from several DataTemplates (according to the type of the item).

  • The DataTemplate belonging to the tb:ToolBarControl is very simple - it just contains ContentPresenter bound to property Content of the tb:ToolBarControl.

  • tb:ToolBarControl is not for technical reasons UserControl, it is just DependencyObject with property Content of type object.

Why can't the ComboBox reference the Window?

Thanks for any help!

Matěj Zábský
  • 16,909
  • 15
  • 69
  • 114
  • Are you sure the failure is from the ComboBox? says window not myWindow but in the error msg it says 'ElementName=myWindow' – Justin XL Nov 23 '11 at 13:56
  • @Xim It is because I have changed names from original. And the binding error specifies its origin. The original full error is "System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=view2D'. BindingExpression:Path=Generator.Maps; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')". And yes, "view2D" is name of the window. – Matěj Zábský Nov 23 '11 at 15:12

1 Answers1

3

I had a similar problem here:

Bindings on child dependency object of usercontrol not working

DependencyObject doesn't have a DataContext and I think that's why the binding doesn't work. Instead of inheriting from 'DependencyObject' try inheriting from FrameworkElement.

Community
  • 1
  • 1
David Masters
  • 8,069
  • 2
  • 44
  • 75
  • I see, but I can't just change the base type to UIElement, because `ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='ToolBarControl'`. Looks like I will have to rewrite the data templates to control templates :( – Matěj Zábský Feb 28 '11 at 15:44
  • I improved my code according to your advice, but it still won't work. I posted a second question: http://stackoverflow.com/questions/7546116/binding-from-items-of-an-itemscontrol-with-custom-collection – Matěj Zábský Sep 25 '11 at 14:25