在 DataTemplate 中绑定 CollectionViewSource
“ContentTemplate”是一个 DataTemplate,它显示一个具有成员“FooList”(ObservableCollection)的对象。
<DataTemplate x:Key="ContentTemplate">
<ListBox ItemsSource="{Binding Path=FOO}">
...
</ListBox>
</DataTemplate>
我需要能够使用 CollectionViewSource 过滤 FooList。这通常是直接的,但我似乎无法让绑定在 DataTemplate 中工作。我尝试这样做:
<DataTemplate x:Key="ContentTemplate">
<DataTemplate.Resources>
<CollectionViewSource x:Key="CVS" Source="{Binding Path=FooList}" Filter="FooFilter"/>
<DataTemplate.Resources>
<ListBox ItemsSource="{Binding Source={StaticResource CVS}}">
我从中得到的错误是:
System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。 BindingExpression:Path=FooList;数据项=空;目标元素是“CollectionViewSource”(HashCode=52991666); target 属性是“Source”(类型“Object”)
在我看来,它正在 CollectionViewSource 上寻找“FooList”,而不是绑定到 DataTemplate 的对象。
那么...我怎样才能让它看到正确的对象呢?
'ContentTemplate' is a DataTemplate that displays an object which has a member 'FooList' (an ObservableCollection).
<DataTemplate x:Key="ContentTemplate">
<ListBox ItemsSource="{Binding Path=FOO}">
...
</ListBox>
</DataTemplate>
I need to be able to filter that FooList using a CollectionViewSource. This is usually been straight forward but I can't seem to get the binding to work within a DataTemplate. I attempted to this:
<DataTemplate x:Key="ContentTemplate">
<DataTemplate.Resources>
<CollectionViewSource x:Key="CVS" Source="{Binding Path=FooList}" Filter="FooFilter"/>
<DataTemplate.Resources>
<ListBox ItemsSource="{Binding Source={StaticResource CVS}}">
The errors I get from this is:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=FooList; DataItem=null; target element is 'CollectionViewSource' (HashCode=52991666); target property is 'Source' (type 'Object')
Which sounds to me like it's looking for 'FooList' on the CollectionViewSource instead of the object bound to the DataTemplate.
So... how do I get this to look at the correct object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我了解,DataTemplate 充当向可视化树中插入内容的指令,但不会成为可视化树本身的一部分。我是在遇到您上面描述的相同问题后才得出这个假设的。我通过将 CollectionViewSource 附加到属于可视化树的元素(在我的例子中是网格)的资源来解决了这个问题。这是有效的示例:
As I understand it, the DataTemplate acts as instructions on what to insert into the visual tree but does not become a part of the visual tree itself. I only came to this hypothesis after running into the same problem you've described above. I fixed the issue by attaching the CollectionViewSource to the resources of an element that would be part of the visual tree, in my case a grid. Here is the sample that did work:
我通过将数据模板移动到用户控件中解决了这个问题。
I worked around this issue by moving the data template into a user control.
我认为您需要绑定到 CollectionViewSource 的视图:
I think you need to bind to the view of the
CollectionViewSource
: