Custom control's content can't bind to parent of the control

纵然是瞬间 提交于 2020-01-04 05:16:09

问题


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!


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!