【问题标题】:Datagrid auto add item with data of parentDatagrid自动添加带有父数据的项目
【发布时间】:2014-01-10 16:35:51
【问题描述】:

我有数据网格,它应该允许用户添加行。但它应该在模型属性之一定义的字段之一中添加项目。有没有人知道怎么做。 像这样的代码:

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>

【问题讨论】:

  • 因此您想添加新的GoodM 项目,其Service 的值将来自OrderWindowModel。是吗?
  • 是的。你是绝对正确的。

标签: c# wpf datagrid


【解决方案1】:

您可以使用后面的代码来做到这一点。在 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;
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-19
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2013-11-18
    • 2013-04-04
    • 2015-10-09
    相关资源
    最近更新 更多