【问题标题】:Binding to a complex object in Silverlight在 Silverlight 中绑定到复杂对象
【发布时间】:2009-11-18 05:12:22
【问题描述】:

我知道它一定是我错过的一些简单的东西。我使用数据服务将数据导入我的 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>

【问题讨论】:

  • 澄清一下,StartTime 是 Lesson 对象的一个​​属性。

标签: wpf silverlight data-binding wpfdatagrid


【解决方案1】:

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

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

但这会呈现数据。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 在渲染 DataGrid 时执行查询。我在网格中得到的行与结果中的对象一样多,它们都是空的。
    【解决方案3】:

    您确定您的 Linq 查询返回任何项目吗?以及包含 StartTime 的任何项目?

    正如我所见,您的查询返回一个包含两个参数的对象,课程和颜色,但不包含 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}"/>
    

    【讨论】:

    • 我的“课程”有属性“DateTime StartTime”,这是我要绑定的字段。
    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    相关资源
    最近更新 更多