【发布时间】:2015-03-25 04:44:32
【问题描述】:
类似于WPF: How to bind to only one item in a collection, not using ItemsControl since I don't want to display all of them,除了集合与主绑定项相关。所有数据都通过 EntityFramework 进来。与链接的问题一样,xaml 解释得最好:
<StackPanel Grid.Row="1" Orientation="Horizontal" DataContext="{Binding CurrentCustomer}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Total Orders:" />
<TextBlock Text="{Binding Orders.Count}" />
</StackPanel >
<StackPanel Orientation="Horizontal">
<TextBlock Text="First Order:" />
<TextBlock Text="{Binding Orders.First.OrderDate}" />
</StackPanel >
</StackPanel>
如您所见,我猜想因为我可以使用“Orders.Count”获得相关订单的计数,所以我尝试使用相同的 linq 语法来尝试检索 Orders.First(我也尝试过 Orders.FirstOrDefault ),但这不起作用。
查看链接的问题,我尝试了Sheridan's '[]' 语法,但 Orders[0].OrderDate 给出的输出错误为:System.Windows.Data Error: 40 : BindingExpression path error: '[]' property not found on 'object' ''HashSet'1' (HashCode=37425772)'. BindingExpression:Path=Orders[0].OrderDate; DataItem='Customer_<BigLongIdentityString>' (HashCode=21972018); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')。
查看他链接到的 msdn 文章,我尝试将表达式括在括号中(根据附加属性)并使用斜杠(当源是集合时)。不出所料,这些也失败了。
谁能告诉我如何获得相关集合中第一项的属性?
【问题讨论】:
-
首先是扩展方法,即
Orders.First().OrderDate? -
@StuartLC 好主意,但没有。同样的错误信息:
BindingExpression path error: 'First()' property not found on 'object' -
@LynnCrumbling 我没看到那个。我不知道如何将 HashSet 更改为 Collection,因为它全是 EF 魔法(我通常也坚持使用 ObservableCollection),但这个答案加上你的第一条评论看起来就像我的问题的答案:在 VM 中创建一个检索的属性HashSet 中日期最早的 Order。你想回答你的cmets,我会接受吗?
-
@mcalex 全部完成;看看我关于 EF 代码生成的 T4 模板的编辑。
-
我记得不久前读过那篇文章(现在你提醒了我)。我认为 EF 向导在生成模型时应该提出一个建议,询问您是否需要处理这些细节的 WPF 可绑定模型。谢谢,问题解决了:-)