Simple CRUD with WPF and data binding

I am new to developing WPF applications for Windows, I just wanted to put it there first. I am using Visual Studio 2010 and the .NET Framework 4.0.

I am working on a fairly simple administration tool. For simplicity, let's say I work with Employee data. I created a small UserControl called UserDetail, which has all the fields related to the Employee class.

What is the easiest way to bind input controls in my UserDetail? This may have a blank screen when creating a new instance or existing values ​​when editing an existing instance.

I tried the following in the constructor:

DataContext = _employee; 

And I linked this control in XAML:

 <TextBox Name="txtFirstName" Text="{Binding FirstName}"/> 

This works, but it doesn't seem like the right way to do it. This seems like a simple example, but I haven't found anything useful yet.

Any suggestions or tutorial links for this kind of easy reference?

+6
windows data-binding wpf
source share
2 answers

Like Joel says you're on the right track. At some point, you need to explicitly specify the DataContext in the code. This will usually be done at the top level - for example, in your Window class, and all subsequent DataContexts should be set via DataBindings.

In your specific example, you say that you are working on UserControl. You should be able to bind the DataContext of the UserDetails control directly where the control is used, and therefore, you do not need to set the DataContext in the code located for the UserControl. At least, usually the user of your UserControl is the one who tells UserControl what data to use.

Say you have an AllEmployees class with the SelectedEmployee property. You set an instance of this object as a DataContext in your window - in the code behind. Now you want your window to display user details for the selected user. The UserDetails control is built on the assumption that it has an Employee object associated with its DataContext, and now you will verify that it has it by setting it to a DataBinding:

 <Window xmlns:local="YourNamespaceHoldingTheUserDetailsControl> .. <local:UserDetails DataContext={Binding SelectedEmployee} /> .. </Window> 

You can also add the Employee property to your UserDetails class, which will set the DataContext - if you think this looks better in the binding.

To improve the separation between the GUI and your domain model, you should definitely learn about the MVVM template . I initially found out that I watched this video several times by Jason Dollinger. The video will tell you a lot of useful things about WPF. This question also has some valuable links on this topic.

Good luck learning WPF! This is slightly different from other graphical interfaces, so the learning curve can be a little steep. But as soon as you do this, this is a wonderful place!

+4
source share

You are actually on the right track.

I recommend you read this article on MV-VM .

+2
source share

All Articles