WPF数据集DataGrid外键绑定

时间:2014-06-10 08:29:07

标签: c# wpf binding datagrid

我在数据集中有两个表:

Schedules
-------------
id INT
schedule_date DATETIME
service_id INT FOREIGN KEY REFERENCES services(id)

Services
-------------
id INT
name VARCHAR

我可以轻松绑定DataGridComboBoxColumn并以下列方式获得我想要的结果:

<DataGridComboBoxColumn Header="Service" 
    ItemsSource="{Binding Source={StaticResource schedulesDataSet}, Path=services}"
    DisplayMemberPath="name"
    SelectedValueBinding="{Binding Path=service_id}" 
    SelectedValuePath="id" />

但是如何使用DataGridTemplateColumn来完成?我想这样做:

<DataGridTemplateColumn Header="Service" Width="*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=services.name}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

但由于我使用的是数据集而不是实体框架,我想这就是为什么它不起作用。

这样做的正确方法是什么?

编辑:

完整的DataGrid代码:

<Grid DataContext="{Binding Source={StaticResource schedulesViewSource}}">
    <DataGrid Margin="0,10,0,0" Grid.Row="1" ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserResizeRows="False" Name="schedulesDataGrid">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Date" Binding="{Binding Path=schedule_date,StringFormat=dd-MMM-yy,ConverterCulture=da-DK}" Width="*" />
            <DataGridTemplateColumn Header="Service" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=services.name}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridComboBoxColumn Header="Status" Width="*" x:Name="scheduleStatusColumn" ItemsSource="{StaticResource ScheduleStatuses}" />
            <DataGridTextColumn Header="Source" Binding="{Binding Path=done_by}" Width="*" />
        </DataGrid.Columns>
    </DataGrid>
</Grid>

1 个答案:

答案 0 :(得分:0)

为您的DataGrid设置ItemsSource

   <DataGrid Margin="0,10,0,0" Grid.Row="1" ItemsSource="{Binding schedulesViewSource, Mode=OneWay}" AutoGenerateColumns="False" CanUserResizeRows="False" Name="schedulesDataGrid">