I'm new to WPF for Windows application development, just wanted to put that out there first. I'm using Visual Studio 2010 and .NET Framework 4.0.
I'm working on a rather simple administration tool. For simplicity sake lets say I'm working with Employee data. I've created a little UserControl called UserDetail that has all the fields that relate to the Employee class.
What is the simplest way to bind the input controls on my UserDetail? This could have a blank screen when creating a new instance, or existing values if editing an existing instance.
I tried the following in the constructor:
DataContext = _employee;
And I bound a control like this in the XAML:
<TextBox Name="txtFirstName" Text="{Binding FirstName}"/>
This works, but it doesn't seem like the correct way to do it. This seems like a simple example, but I haven't found anything helpful yet.
Any suggestions or links to an tutorial for this sort of simple binding?
Like Joel says you're on the right track. At some point you need to explicitly set the DataContext in the code behind. This will typically be done on a top level - like in your Window class - and all further DataContext's should be set through DataBindings.
For your specific example you say you're working on a UserControl. You should be able to bind the DataContext of the UserDetails control directly where the control is being used, and hence you shouldn't need to set the DataContext in the code behind for the UserControl. At least normally the user of your UserControl is who would tell the UserControl which data to use.
Let's say you have a class AllEmployees with a property SelectedEmployee. You set an instance of this object as DataContext on your Window - in the code behind. Now you want your window to show user details for the SelectedEmployee. The UserDetails control is built assuming it has an Employee object bound to its DataContext, and now you make sure it has one by setting this in a DataBinding:
<Window xmlns:local="YourNamespaceHoldingTheUserDetailsControl>
..
<local:UserDetails DataContext={Binding SelectedEmployee} />
..
</Window>
You can also add an 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 definitly learn about the MVVM pattern. I initially learned from watching this video by Jason Dollinger a few times. The video will teach you a lot of useful things about WPF. This question also seems to have some valuable links on the subject.
Good luck learning WPF! It's a bit different from other GUI frameworks, so the learning curve might be a bit steep. But once you get into it it's a wonderful place to be!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With