Drag and drop from datasource to WPF window not working

后端 未结 2 1454
野性不改
野性不改 2020-12-02 02:04

I have been tasked to design a contact management program for my company. We have VS 2012 and since I have never used WPF before I thought I would use it to develop this app

2条回答
  •  时光取名叫无心
    2020-12-02 02:58

    Automatically Create Data Grids from Your Models

    Using a data source to drag and drop a template onto a WPF control is an excellent and fast way to get up and running!

    Start by doing this: In your project create a folder named Models, then use either Entity Framework DB first or code by hand the models you want to show.

    In that same folder create a dummy class that is a property for IEnumerable like this..

    public IEnumerable MyCollection { get; set; }
    

    From there go to the Main Visual Studio menu, to View/Other Windows/Data Source and click that link.

    Data Source Wizard

    Click on Object and find the MyCollection property just created above.

    Now open a user control or window in WPF but keep the datasources toolbox opened.

    It should default to a DataGrid, but you can right click on the datasource and change it to detail, datagrid or select individual properties of the class it represents.

    Simply drag that datasource onto the XAML's grid area. The right click on the new stuff you see and click reset to set the content to be the size of the entire window.

    After having done this you will have code injected into the code behind of the view as follows in the window loaded event of that window, usercontrol etc.

            // Do not load your data at design time.
             if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
             {
                //Load your data here and assign the result to the CollectionViewSource.
                System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
                myCollectionViewSource.Source = your data
            // }
    

    Go back to the XAML and look for the CollectionViewSource KEY property that was also inserted when you dragged the property to the XAML. It looks like this:

    Collection View Source KEY

    Use the Key name in the code behind, and then "Bind" the CVS to your data source which is an enumerable of type MyClassModel it can live in the View Model or in the code behind of the view as you choose.

    If you only use the CollectionViewSource to as the datacontext of the grid you do not need to implement INPC for any underlying collections! The CVS updates the view automatically everytime the source is updated! Once you get good at this you can create working View prototypes of data in 2 minutes! Forget hand-coding XAML that just takes too long.

提交回复
热议问题