绑定到Silverlight中的复杂对象

时间:2009-11-18 05:12:22

标签: wpf silverlight data-binding wpfdatagrid

我知道我错过了一些简单的事情。我使用数据服务将数据导入我的silverlight应用程序。当我将数据绑定到我的数据网格时,它就像一个魅力

LessonGrid.ItemsSource = context.Lessons

然而,只要我尝试将对象包装到更复杂的数据结构中,它就会停止工作

LessonGrid.ItemsSource = context.Lessons.Select(l => new {Lesson = l; Color=Colors.Yellow})

我尝试使用路径定义绑定,但没有,似乎无法正常工作

<data:DataGridTextColumn Header="Date" Binding="{Binding StartTime}"/>
<data:DataGridTextColumn Header="Date" Binding="{Binding StartTime, Path=Lesson.StartTime}"/>
<data:DataGridTextColumn Header="Date" Binding="{Binding Path=Lesson.StartTime}"/>
<data:DataGridTextColumn Header="Date" Binding="{Binding StartTime, Path=Lesson}"/>

建议?


经过更多研究后:

好吧,这与复杂的对象无关。即使这段代码显示两行但没有数据。我错过了什么?

LessonGrid.ItemsSource = 
new[] {new {Color = Colors.Yellow,StartTime = 12, Text="text"}, 
new {Color = Colors.Red, StartTime = 14, Text="text3"}}; 

XAML:

<data:DataGrid x:Name="LessonGrid" AutoGenerateColumns="True" Height="375" IsReadOnly="True"> </data:DataGrid>

3 个答案:

答案 0 :(得分:2)

好的,我自己想通了。它是关于绑定不喜欢的隐式类型的东西。这显示空网格

LessonGrid.ItemsSource = new[] {new {StartTime = 111, Text = "hi there"}};

但这会呈现数据。

LessonGrid.ItemsSource = new[] {new Temp {StartTime = 111, Text = "hi there"}};

答案 1 :(得分:0)

您已创建Linq查询但尚未实际执行。为了实际执行,你必须做类似.ToList()的事情 试试这个:

 LessonGrid.ItemsSource = context.Lessons.Select(l => new {Lesson = l; Color=Colors.Yellow}).ToList();

答案 2 :(得分:0)

您确定Linq查询是否会返回任何项目?还有包含StartTime的任何项目?

我可以看到你的查询返回一个包含两个参数Lesson和Color但不是StartTime的对象。我猜参数之间的分隔符应该是逗号(,)。

LessonGrid.ItemsSource = context.Lessons.Select(l => new {Lesson=l, Color=Colors.Yellow, StartTime=12});

然后,您可以绑定到DataGrid中的属性:

<data:DataGridTextColumn Header="Date" Binding="{Binding StartTime}"/>
or
<data:DataGridTextColumn Header="Date" Binding="{Binding Path=StartTime}"/>