问题
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
isUserControl
which contains actualToolBar
withItemsSource
bound to theItems
property of thetb:ToolBar
(of type inheritingIList
).The
ToolBar
'sToolBarItem
DataTemplate
is chosen from severalDataTemplate
s (according to the type of the item).The DataTemplate belonging to the
tb:ToolBarControl
is very simple - it just containsContentPresenter
bound to propertyContent
of thetb:ToolBarControl
.tb:ToolBarControl
is not for technical reasonsUserControl
, it is justDependencyObject
with propertyContent
of 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