如何在单击时将数据从数据网格行(form2)发送到已打开form2的usercontrol(form1)中的另一数据

时间:2019-04-30 07:35:00

标签: c# .net wpf entity-framework data-binding

单击按钮“ Ajouter ce Produit”后如何发送数据,如您所见,并将SelectedItem发送到我的主窗体中的userControl到其datagrid上,请帮助!

这是我在userControl上打开的窗口,希望从其中复制: the image;

这是我要在打开的窗口中接收selectedItem的用户控件中的datagird: the Image

1 个答案:

答案 0 :(得分:0)

当您单击form1中的按钮时可以引发一个事件,而在form2中您可以侦听该事件并将所选项目传递给form2。

   // The form that you want to copy the item from
public class form1
{
// This is the event that will be raised when you click the button.
public event EventHandler<ShareSelectedItemEventArgs> ShareSelectedItemData;

//This is where you click your button in form1
private void Ajuoter_ce_Produit_Click(object sender, EventArgs args)
{
 if(ShareSelectedItemData != null)
     ShareSelectedItemData(this, new ShareSelectedItemEventArgs() { ProductItem = (ProductItem)datagrid1.SelectedItem});
   }
}
// The form to send the data to
public class form2
{
    public form2()
    {
        // Listen for the event in form1 here
        form1.ShareSelectedItemData += (object sender, ShareSelectedItemEventArgs args) => ListenForItem(sender, args);
    }

    private void ListenForItem(object sender, ShareSelectedItemEventArgs args)
    {
        //handle the display of your item here.
        // The selected item can be accessed through args.ProductItem
    }
}

public class ShareSelectedItemEventArgs : EventArgs
{
    // This is the product item in your api or whatever you may have called it
    // it contains properties of price, name etc.
    public Product ProductItem { get; set; }

    public ShareSelectedItemEventArgs() : base()
    {
    }
}

希望这会有所帮助。我发现事件在不破坏封装概念的情况下在共享数据方面非常强大。