I feel like I’m missing a fairly fundamental concept to WPF when it comes to databinding, but I can’t seem to find the right combination of Google keywords to locate what I’m after, so maybe the SO Community can help. 🙂
I’ve got a WPF usercontrol that needs to databind to two separate objects in order to display properly. Both objects must be dynamically set from an outside source. Thus far I’ve simply been using the DataContext property of the form for dynamic object binding, but that only allows for one object to be referenced. I feel like this is a simple problem and that I must be missing something obvious.
My previous attempt looks something like this:
<UserControl.Resources> <src:Person x:Key='personSource' /> <src:Job x:Key='jobSource' /> </UserControl.Resources> <TextBox Text='{Binding Source={StaticResource personSource}, Path=Name' /> <TextBox Text='{Binding Source={StaticResource jobSource}, Path=Address' />
This will bind to any defaults I give the classes just fine, but If I try to dynamically set the objects in code (as I show below) I don’t see any change.
Person personSource = FindResource('personSource') as Person; personSource = externalPerson; Job jobSource= FindResource('jobSource') as Job; jobSource = externalJob;
What am I missing?
I would probably use a CustomControl with two DependencyProperties. Then the external site that uses your custom control could bind the data that they want to that control, also by using a custom control you can template the way the control looks in different situations.
Custom control code would look something like:
Generic.xaml is a file that should be created for you and could have a Style that looks something like this:
Finally, when you go to use your control you would do something like this.