自定义控件的内容无法绑定到控件的父级
我有以下 XAML(简化,没有结束标签):
<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
的绑定将失败
找不到绑定源 参考'ElementName=myWindow'
有关自定义控件的一些事实:
tb:ToolBar
是UserControl
,其中包含实际的ToolBar
和ItemsSource
绑定到tb:ToolBar
的Items
属性(继承IList
的类型)。ToolBar
的ToolBarItem
DataTemplate
是从多个DataTemplate
中选择的(根据item)。属于
tb:ToolBarControl
的DataTemplate非常简单 - 它只包含绑定到tb的属性
.Content
的ContentPresenter
:ToolBarControltb:ToolBarControl
不是出于技术原因UserControl
,它只是DependencyObject
,其属性为Content
类型object
.
为什么ComboBox
不能引用Window
?
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这里遇到了类似的问题:
Bindings on child dependency object用户控件不起作用
DependencyObject 没有 DataContext,我认为这就是绑定不起作用的原因。不要从“DependencyObject”继承,而是尝试从 FrameworkElement 继承。
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.