INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

MVVM & EF - What am I binding to what?

MVVM & EF - What am I binding to what?

(OP)
Hi,

I seem to be going round in circles trying to learn MVVM from : https://msdn.microsoft.com/en-us/library/gg430857(...

Can someone please explain what model I am binding to what?

I want a view that displays a list of records from the SQL DB.

I am using Entity Framework.

I cannot find any info on how to do this while looking at the PRISM documentation and MVVM?

Whats the model, what's the viewmodel?

Where does the data come from, how do I bind it to a DataGrid control in my view?

Your help is much appreciated.

Thanks,
1DMF


"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: MVVM & EF - What am I binding to what?

(OP)
Well I've kind of got somewhere...

I have my main view (shell)

CODE

<Window x:Class="Financial_Promotions.Financial_Promotions_Main"
        xmlns:prism="http://www.codeplex.com/prism"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="HLP Financial Promotion Approvals" Height="300" Width="300" Closed="Window_Closed">
        <ItemsControl Name="MainRegion" prism:RegionManager.RegionName="MainRegion" />
</Window> 

Which injects my view

CODE

public class FinancialPromotionsModule : IModule
    {
        private readonly IRegionManager regionManager;

        public void Initialize()
        {
            regionManager.RegisterViewWithRegion("MainRegion", typeof(Views.FinancialPromotionsView));
        }

        public FinancialPromotionsModule(IRegionManager regionManager)
        {
            this.regionManager = regionManager;
        }


    } 

My view (user control) instantiates the ViewModel

CODE

public partial class FinancialPromotionsView : UserControl
    {
        public FinancialPromotionsView()
        {
            InitializeComponent();
            this.DataContext = new Financial_Promotions_Module.ViewModels.FinancialPromotionsViewModel();
        }

    } 

My ViewModel generates the the collection of EF DB records

CODE

class FinancialPromotionsViewModel : BindableBase
    {
        private ObservableCollection<Financial_Promotion> fp;

        public FinancialPromotionsViewModel()
        {
            fp = LoadFP("Pending");
        }

        public ObservableCollection<Financial_Promotion> FinancialPromotions
        {
            get { return this.fp; }
            set { SetProperty(ref this.fp, value); }
        }

        /// <summary>
        /// Returns a collection of Financial Promotion records based on status
        /// </summary>
        /// <param name="status">Status of promotions</param>
        /// <returns>Collections of FP entities</returns>
        private ObservableCollection<Financial_Promotion> LoadFP(string status)
        {
            using (var hlp = new HLP())
            {
                // Get FP's
                return new ObservableCollection<Financial_Promotion>(hlp.Financial_Promotion
                    .Where(b => b.Status == status).ToList());
            }
        }

    } 

Which is bound to my view

CODE

<Grid>
        <DataGrid ItemsSource="{Binding FinancialPromotions }" Height="278" VerticalAlignment="Bottom"  />
    </Grid> 

I think this is correct, but would appreciate some input to guide me.

Also what I don't get is where do I now put the buttons for altering the view (changing the status of displayed records).

Is it a separate view, pushed into another region on the shell view and then how does a ViewModel interact with another?

Or if they are controls to manipulate another UI control, is that considered to be the one View / ViewModel?

Cheers,
1DMF

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: MVVM & EF - What am I binding to what?

(OP)

Quote:

Also what I don't get is where do I now put the buttons for altering the view (changing the status of displayed records).

Is it a separate view, pushed into another region on the shell view and then how does a ViewModel interact with another?

I think I have found the possible answer through "Solution Commanding", utilising DelegateCommand / CompositeCommand.

I assumed there would be some kind of event listening / triggering involved, digging through the documentation is like swimming in treacle, slow and messy!

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: MVVM & EF - What am I binding to what?

Model: EF model, you will just need one edmx for the whole application.
ViewModel: This makes use of the model to load data, uses the navigation properties to load related data, you may use Linq here, or the extension methods linq is based on. Load data into fields, collections, especially generic ones.
View: The UI frontend, it binds to the ViewModel.

So despite of TwoWay Binding we have a one way knowledge or flow of control of the components of each other: The View knows and controls it's Viewmodel, the Viewmodel knows and controls the Model. This distinguishes it from model/view/controller, where the controller compares to a viewmodel, but (inn a web app) requests of the ui go to the/a controller and it builds up the (next) view (eg html). Because you don't do that in MVVP, it's hard at design time. One important ease of implementing the view is to have a design instance of a view model to get intellisense in writing XAML, look into d:Designinstance.


Take a look at Caliburn Micro (http://caliburnmicro.com/). It's taking some burden from you in making the initialisations and bindings. It binds by a simple convention: The name of a WPF control in your view will be bound to the same field of the viewmodel. And another name convention is the suffix of classes is coupling view and viewmodel, simply by having eg shellview, shellviewmodel, these belong together, another possible way is going by the namespaces, eg a View and ViewModel folder both hold a Shell.cs (IIRC, I use the other convention).

Aside of that you have a bootstrapper and base classes all inherit and implement NotifyPropertyChange, a very important concept of letting each change trigger refresh of all other view parts or even other views. The concept of Commands/Actions also is covered by name conventions. And psst, if you base your viewmodel on the caliburn micro screen cöass, the viewmodel can find out it's view, too, via the GetView mothod, but actually this is introducing a dependency you typically don't want in that architcture.

That said the disadvantage is, while it simplifies MVVM you don't learn the basics, as they is simply done for you by Calliburn Micro. And it needs additional work, if you introduce controls working slightly different than the native WPF controls, eg Telerik. There is an instrument for that in Caliburn, too, it allows you to define further conventions for other controls. And the support of the developers and community also helps with that.

It's really worth looking at anyway, as it shows how you could go about things and you can of course look into the implementation of it to learn from it instead of using it or in parallel to using it.

Bye, Olaf.

RE: MVVM & EF - What am I binding to what?

(OP)
Hi Olaf,

Thanks for the reply, it is very helpful.

I finally got somewhere Friday afternoon, using PRISM / UNITY, I couldn't get my head round how the MEF example StockTrader app worked, so hacked away with UNITY and finally got my app working.

It's been an uphill struggle trying to learn so many new concepts / paradigms and frameworks not to mention the language itself (C#,EF,MVVM,XAML,PRISM,UNITY), having been on just a couple of crash courses in C#.

As I suffer with Dyspraxia, it means it takes a while for it all to sink in and can be difficult struggling with the frustration when I get a mind block, so I guess it's just as well I'm tenacious!

Simple things like the superfluous interfaces that need to wrap your ViewModels to enable registration for dependency injection of arguments such as the EventAggregator was very difficult to work out, but I think I now have a preliminary understanding that has at least got me further towards a working app.

Interfaces is one part of the C# language I really struggle with, I understand their syntax, what it means to implement them, how they define data typing with specific functionality, but I have a blank spot with knowing where I need to create them in my own app, and how they fit within an application design.

Part of the problem with Dyspraxia is assigning meaning to things that are so abstract and none of the courses I have been on have been able to provide a concrete explanation of where to use them and why. So it is not surprising I had difficulty with the UNITY dependency injection, when the interface doesn't even define any common properties or behaviour signatures, I guess it's simply a data typing wrapper mechanism?

I also made a silly faux pas in my ViewModel , where I was updating in the private internal attribute instead of the exposed public property that wraps it, which is why I guess the property uses SetProperty in the setter to trigger the NotifyPropertyChange to update the view, all inherited from the BindableBase class of the framework.

I still have a way to go to learn how to work with my regions in the Shell view (main window), implement view navigation and I also want to use view transitions, but I do at least seem to be getting somewhere.

Regards,
1DMF

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: MVVM & EF - What am I binding to what?

Hi 1DMF,

I share your pain, not that I have Dyspraxia, but it's also still an uphill struggle for me to learn the basics, just because I get older, too. I tend to put .NET aside and go back to old times with PHP & HTML. The main feeling I have about .NET is MS cranked in every idea and wish they collected from developers. In the end you have a very universally usable language and the overall conception might also be well thought of, but the result is you have so many options it's much easier to use them wrong and not working in conjunction with each other, than getting something workable, maintainable, extensible.

If you understand class inheritance you already also almost understand interfaces and when to define them. Interfaces have limitations, eg you can't implement code, which would be inherited, which you can do in (abstract) classes. What makes classes less versatile than interfaces is, you can only inherit from one class, but you can implement many interfaces. What makes classes more versatile is once you upgrade them all child classes inheriting it upgrade, too.

Interfaces are best suited for defining a contract to a common functionality also otherwise unrelated classes may need or want to implement. Interfaces therefore should just have a single, smaller purpose you don't need to extendd, as it's next to impossible to extend them. That'd need an extension of any class inheriting the interface, which is only applicable, if you maintain all these classes. Remember, if you add a method definition you add a task for the developer of a class to implement that, instead of just inheriting it. Extending a base class (no matter if the root abstract class or not) you often also need to change implementations in child classes to make use of the extension, but you have the option of not doing anything. You can make a backward compatible change in a class, while you can't make any change in an interface needing no action on the implementation side.

Sounds like you rather would want an abstract class everything inherits from, but then you have the inheritance chain hindering you from doing that and even if you could, you'd make that a god class for anything, while interfaces can define little contracts you can rely on later. You can have generic code acting on instances via a certain interface and you can even simply see, whether an instance implements an interface without slow reflection, you cast some instance AS Interface and if that's not null you can make use of the interface structure.

Bye, Olaf.

RE: MVVM & EF - What am I binding to what?

(OP)

Quote:

just because I get older, too. I tend to put .NET aside and go back to old times with PHP & HTML
For sure! , Though I prefer Perl than PHP.

I can see how Interfaces work, I also appreciate the pitfalls in altering one and the implications it has on any class that implements them. What I need experience and help with is understanding how you identify common behavior that can be used by generic code across multiple class types.

When I took my OU course in databases, it guided you step by step through the waterfall method analysing plain text from the domain of discourse (establishing requirements), right through to the schema design, which taught me processes to analyse the problem, identify the constituent parts and design the solution.

This is the type of support / tutoring I think I need to help me see the bigger picture.

However, the OU doesn't even know what C# is, so no courses, plus with the tuition fees debacle the standard course quadrupled in price, so it hindered any possibility of me converting my Diploma into a Degree!

I've looked at boot camp style tuition, but that's aimed at specific MS certification, not generic software design tuition.

Do you have any ideas on where I might look for this type of support / tuition?

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: MVVM & EF - What am I binding to what?

Good question, but you ask the wrong guy in that aspect. I'm rather auto didactic than taking courses or certifications. I'd look out for OOP books specifically covering C# and see whether they have a longer section about interfaces, too.

All I can say is the interfaces don't come out automatic in a process of designing like the 4th normal form in database design comes out in a standardized way of normalizing data. The need for interfaces also rather is about the class behavior/functionality design than about the data, though you put in attributes in them. See at it this way: Without common attributes of all classes implementing your interface, you can't write code addressing any common attributes, the code implementation of course is individual per class, but the use of knowing a class implements a certain interface is in code outside of the classes themselves, handling several types/classes, as long as they all implement a certain interface, as you can rely on the interface attributes (properties/fields) and methods to exist.

Bye, Olaf.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close