自定义控件的内容不能绑定到控件的父级 [英] Custom control's content can't bind to parent of the control
问题描述
我有以下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
isUserControl
which contains actualToolBar
withItemsSource
bound to theItems
property of thetb:ToolBar
(of type inheritingIList
).
工具栏
的 ToolBarItem
DataTemplate
从几个 DataTemplate
中选择(根据类型
The ToolBar
's ToolBarItem
DataTemplate
is chosen from several DataTemplate
s (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:
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屋!