自定义控件的内容不能绑定到控件的父级 [英] Custom control's content can't bind to parent of the control

查看:131
本文介绍了自定义控件的内容不能绑定到控件的父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下XAML(简化的,没有结尾的标签):

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}">

但是, ComboBox 的绑定将失败with


But the ComboBox's binding will fail with


找不到与
绑定的源引用'ElementName = myWindow'

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

有关自定义控件的一些事实:

Some facts about the custom controls:


  • tb:ToolBar UserControl ,其中包含实际的 ToolBar ItemsSource 绑定到项目属性 tb:ToolBar (继承 IList )。

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

工具栏 ToolBarItem DataTemplate 从几个 DataTemplate 中选择(根据类型

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

属于 tb:ToolBarControl 的DataTemplate非常简单 - 它只是包含 ContentPresenter 绑定到的属性内容 tb:ToolBarControl

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

t b:ToolBarControl 不是出于技术原因 UserControl ,它只是 DependencyObject 与属性内容类型为对象

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

为什么 ComboBox 不能引用窗口

感谢任何帮助!

推荐答案

这里有一个类似的问题:

I had a similar problem here:

WPF绑定关于用户控件的子依赖对象不工作

DependencyObject没有DataContext,我认为这就是绑定不起作用的原因。而不是继承'DependencyObject',尝试从FrameworkElement继承。

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.

这篇关于自定义控件的内容不能绑定到控件的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆