与 ElementName 绑定不起作用
以下是 XAML:
<DataGrid Grid.Column="0" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding Path=Columns}"
x:Name="ColumnsGrid" RowHeaderWidth="0">
<DataGrid.Columns>
<DataGridTextColumn Width="*" Binding="{Binding Path=Header}"
Header="{Binding ElementName=ColumnsGrid, Path=DataContext.Count, StringFormat=Columns ({0}), diag:PresentationTraceSources.TraceLevel=High}"/>
</DataGrid.Columns>
</DataGrid>
绑定返回错误:System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。
我想念什么?
更新:
这里发生了什么? Columns 集合只是一个属性 在数据网格中;该集合不符合逻辑(或视觉) 树,因此 DataContext 没有被继承,这导致 没有任何东西可以绑定。
更新2: 关于 DataGrid 警告的好文章:http://blogs.msdn.com/b/vinsibal/archive/2009/04/07/5-random-gotchas-with-the-wpf-datagrid.aspx
Here is the XAML:
<DataGrid Grid.Column="0" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding Path=Columns}"
x:Name="ColumnsGrid" RowHeaderWidth="0">
<DataGrid.Columns>
<DataGridTextColumn Width="*" Binding="{Binding Path=Header}"
Header="{Binding ElementName=ColumnsGrid, Path=DataContext.Count, StringFormat=Columns ({0}), diag:PresentationTraceSources.TraceLevel=High}"/>
</DataGrid.Columns>
</DataGrid>
Binding returns error: System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element.
What do I miss?
Update:
Here is the answer:
http://blogs.msdn.com/b/jaimer/archive/2008/11/22/forwarding-the-datagrid-s-datacontext-to-its-columns.aspx
What is happening here? The Columns collection is just a property
in the Datagrid; this collection is not in the logical (or visual)
tree, therefore the DataContext is not being inherited, which leads to
there being nothing to bind to.
Update 2:
Good article about DataGrid's caveats: http://blogs.msdn.com/b/vinsibal/archive/2009/04/07/5-random-gotchas-with-the-wpf-datagrid.aspx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
绑定
DataGridColumn
的Header
abdVisibility
属性需要特殊处理...请参阅此...
绑定数据网格列可见性MVVM
Binding on
DataGridColumn
forHeader
abdVisibility
properties needs special treatment...See this...
Bind datagrid column visibility MVVM
如果您对 DataContext 中引用的对象的 Count 属性感兴趣,请尝试使用常规数据绑定:
编辑
显然数据网格的列不是视觉的一部分树
所以使用ElementName和RelativeSource是行不通的。
也许您应该将该属性添加到列绑定到的对象中。
If you are interested in the Count property of the object that is referred to in the DataContext you try and use regular databinding:
EDIT
Apparently the columns of a datagrid are not part of the Visual Tree
So using ElementName and RelativeSource will not work.
Perhaps you should add the property to the object the column is bound to.