code_junkie

Exposing Multiple Databinding sources

Nov 12th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. <UserControl.Resources>
  2. <src:Person x:Key="personSource" />
  3. <src:Job x:Key="jobSource" />
  4. </UserControl.Resources>
  5. <TextBox Text="{Binding Source={StaticResource personSource}, Path=Name" />
  6. <TextBox Text="{Binding Source={StaticResource jobSource}, Path=Address" />
  7.  
  8. Person personSource = FindResource("personSource") as Person;
  9. personSource = externalPerson;
  10. Job jobSource= FindResource("jobSource") as Job;
  11. jobSource = externalJob;
  12.  
  13. public class CustomControl : Control
  14. {
  15. public static readonly DependencyProperty PersonProperty =
  16. DependencyProperty.Register("Person", typeof(Person), typeof(CustomControl), new UIPropertyMetadata(null));
  17. public Person Person
  18. {
  19. get { return (Person) GetValue(PersonProperty); }
  20. set { SetValue(PersonProperty, value); }
  21. }
  22.  
  23.  
  24. public static readonly DependencyProperty JobProperty =
  25. DependencyProperty.Register("Job", typeof(Job), typeof(CustomControl), new UIPropertyMetadata(null));
  26. public Job Job
  27. {
  28. get { return (Job) GetValue(JobProperty); }
  29. set { SetValue(JobProperty, value); }
  30. }
  31.  
  32. static CustomControl()
  33. {
  34. DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));
  35. }
  36. }
  37.  
  38. <ResourceDictionary
  39. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  40. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  41. xmlns:local="clr-namespace:WpfApplication3">
  42.  
  43.  
  44. <Style TargetType="{x:Type local:CustomControl}">
  45. <Setter Property="Template">
  46. <Setter.Value>
  47. <ControlTemplate TargetType="{x:Type local:CustomControl}">
  48. <Border Background="{TemplateBinding Background}"
  49. BorderBrush="{TemplateBinding BorderBrush}"
  50. BorderThickness="{TemplateBinding BorderThickness}">
  51. <StackPanel>
  52. <TextBox Text="{TemplateBinding Person.Name}" />
  53. <TextBox Text="{TemplateBinding Job.Address}" />
  54. </StackPanel>
  55. </Border>
  56. </ControlTemplate>
  57. </Setter.Value>
  58. </Setter>
  59. </Style>
  60. </ResourceDictionary>
  61.  
  62. <src:CustomControl Person="{Binding Person}" Job="{Binding Job}" />
  63.  
  64. DataContext="{Binding RelativeSource={RelativeSource Self}}"
  65.  
  66. <TextBox Text="{Binding Path=Person.Name" />
  67. <TextBox Text="{Binding Path=Job.Address" />
  68.  
  69. <TextBox Text="{Binding Source=Person, Path=Name" />
  70. <TextBox Text="{Binding Source=Job, Path=Address" />
Add Comment
Please, Sign In to add comment