问题
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:ToolBarisUserControlwhich contains actualToolBarwithItemsSourcebound to theItemsproperty of thetb:ToolBar(of type inheritingIList).The
ToolBar'sToolBarItemDataTemplateis chosen from severalDataTemplates (according to the type of the item).The DataTemplate belonging to the
tb:ToolBarControlis very simple - it just containsContentPresenterbound to propertyContentof thetb:ToolBarControl.tb:ToolBarControlis not for technical reasonsUserControl, it is justDependencyObjectwith propertyContentof typeobject.
Why can't the ComboBox reference the Window?
Thanks for any help!
回答1:
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.
来源:https://stackoverflow.com/questions/5144009/custom-controls-content-cant-bind-to-parent-of-the-control