Datagrid自动添加包含父数据的项目

时间:2013-12-22 06:38:12

标签: c# wpf datagrid

我有datagrid,应该允许用户添加行。但它应该添加项目,其中一个字段由其中一个模型属性定义。有人知道如何做到这一点。 像这样的代码:

public class OrderWindowModel : BaseModel
{
    public ObservableCollection<GoodM> Goods { get; set; }
    public Service Service { get; set; }
}

public class GoodM : BaseModel
{
    public Service Service { get; set; }
    public List<Good> Goods
    {
        get{ return Service.GoodsL; }
    }

    public Good CurrGood { get; set; }
}

和xaml

<custom:DataGrid Margin="5" Grid.Row ="1" CanUserAddRows="True" CanUserDeleteRows="True" 
            AutoGenerateColumns="False" SnapsToDevicePixels="True" SelectedIndex="0" 
            CanUserReorderColumns="True" ItemsSource="{Binding Goods}" Grid.ColumnSpan="2">
    <custom:DataGrid.Columns>
        <custom:DataGridComboBoxColumn Header="Товар" DisplayMemberPath="{Binding Name}" 
                        SelectedItemBinding="{Binding CurrGood}"  ItemsSource="{Binding Goods}" Width="*">
        </custom:DataGridComboBoxColumn>
    </custom:DataGrid.Columns>
</custom:DataGrid>

1 个答案:

答案 0 :(得分:4)

你可以使用背后的代码来做到这一点。在XAML中挂钩InitializingNewItem事件:

<DataGrid InitializingNewItem="DataGrid_InitializingNewItem"/>

在处理程序中,您将添加NewItem,您可以在其中设置字段的值:

private void DataGrid_InitializingNewItem(object sender,
                                          InitializingNewItemEventArgs e)
{
    if (e.NewItem != null)
    {
       ((GoodM)newItem).Service = // Set value here;
    }
}
相关问题