DataGrid自动添加带有父数据的项目 [英] Datagrid auto add item with data of parent

查看:33
本文介绍了DataGrid自动添加带有父数据的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have datagrid, which should allow user add row. But it should add item where one of the field defined by the one of the model properties. Have anybody an idea how to do it. Code like this:

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>


推荐答案

您可以使用后面的代码来实现。挂钩到XAML中的 InitializingNewItem 事件:

You can do that using code behind. Hook to InitializingNewItem event in your XAML:

<DataGrid InitializingNewItem="DataGrid_InitializingNewItem"/>

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

In the handler you will get NewItem added where you can set the value for your field:

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

这篇关于DataGrid自动添加带有父数据的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆