WPF使用ID从数据库表绑定DataGrid列ComboBox

时间:2018-11-12 23:34:09

标签: c# wpf xaml binding datacontext

我上课

[Table(Name = "Categories")]
class Category
{
    [Column(Name = "CategoryID", IsPrimaryKey = true, IsDbGenerated = true)]
    private int CategoryID { get; set; }
    [Column(Name = "Name")]
    public string Name { get; set; }
}

[Table(Name = "Products")]
class Product
{
    [Column(Name = "ProductID", IsPrimaryKey = true, IsDbGenerated = true)]
    public int ProductID { get; set; }
    [Column(Name = "CategoryID")]
    public int CategoryID { get; set; }
    [Column(Name = "Name")]
    public string Name { get; set; }
    [Column(Name = "Price")]
    public double Price { get; set; }
}

我需要使用产品中的CategoryID将DataGrid列创建为ComboBox,并将所有类别中的所有类别放入ComboBox中进行编辑,我如何使用DataContext做到这一点

1 个答案:

答案 0 :(得分:0)

在这里,我在窗口级别中创建了名称为ProductSet&ListOfCategory的产品和类别的ObservableCollection。

public ObservableCollection<Category> ListOfCategory { get; set; }
public ObservableCollection<Product> ProductSet  { get; set; }

我已经在Window后面的代码中创建了ObservableCollection,您可以在视图模型中创建此方法,这种方法更好。

我已将窗口命名为“ Window1” x:Name =“ Window1”

当您需要绑定数据上下文时,请使用Window1进行elementBinding并设置ItemsSource =“ {Binding ProductSet}”。因此,这里发生的是在ProuctSet中搜索DataContext,然后在Window1类中搜索DataContext。

对于DataGridComboBoxColumn,使用样式设置ItemsSource,并使用相对源搜索具有ListOfCategory的Datagrid DataContext。

<DataGrid AutoGenerateColumns="False" x:Name="DataGrid1" HorizontalAlignment="Left" Height="135" Margin="21,288,0,0" VerticalAlignment="Top" Width="729" DataContext="{Binding ElementName=Window1}" ItemsSource="{Binding ProductSet}" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="ProductID" Width="175" Binding="{Binding ProductID}"></DataGridTextColumn>
            <DataGridComboBoxColumn   Header="Category"    DisplayMemberPath="Name" SelectedValuePath="CategoryID" SelectedItemBinding="{Binding ListOfCategory}">
                <DataGridComboBoxColumn.ElementStyle>
                    <Style TargetType="ComboBox">
                        <Setter Property="ItemsSource" Value="{Binding Path=DataContext.ListOfCategory, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
                    </Style>
                </DataGridComboBoxColumn.ElementStyle>
                <DataGridComboBoxColumn.EditingElementStyle>
                        <Style TargetType="ComboBox">
                        <Setter Property="ItemsSource" Value="{Binding Path=DataContext.ListOfCategory,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
                    </Style>
                    </DataGridComboBoxColumn.EditingElementStyle>
    </DataGridComboBoxColumn>
        <DataGridTextColumn Header="Name" Width="175" Binding="{Binding Name}"></DataGridTextColumn>
        <DataGridTextColumn Header="Price " Width="175" Binding="{Binding Price }"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

如果要使用View模型进行绑定,请提供Viewmodel的类名而不是元素绑定。