Skip to main content
 首页 » 编程设计

c#之Datagrid自动添加带有父数据的项目

2024年02月13日13落叶无声

我有数据网格,应该允许用户添加行。但它应该在模型属性之一定义的字段之一的位置添加项目。让任何人知道如何去做。 代码如下:

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> 

请您参考如下方法:

您可以使用隐藏代码来做到这一点。 Hook 到 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; 
    } 
}