Guest User

Why does this simple databinding scenario not work (ComboBox related)

a guest
Feb 26th, 2012
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. <UserControl x:Class="SilverlightApplication2.Page"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Width="400" Height="300">
  5.  
  6. <UserControl.Resources>
  7. <DataTemplate x:Key="icTemplate">
  8. <ComboBox ItemsSource="{Binding StringsChild}" SelectedItem="{Binding SelectedItem}"/>
  9. </DataTemplate>
  10. </UserControl.Resources>
  11.  
  12. <Grid x:Name="LayoutRoot" Background="White">
  13. <Grid.RowDefinitions>
  14. <RowDefinition/>
  15. <RowDefinition/>
  16. </Grid.RowDefinitions>
  17. <ItemsControl x:Name="ic" ItemTemplate="{StaticResource icTemplate}">
  18. <ItemsControl.ItemsPanel>
  19. <ItemsPanelTemplate>
  20. <StackPanel Orientation="Vertical"/>
  21. </ItemsPanelTemplate>
  22. </ItemsControl.ItemsPanel>
  23. </ItemsControl>
  24.  
  25. <Button Click="Save" Grid.Row="1" Content="GO"/>
  26. </Grid>
  27.  
  28. namespace SilverlightApplication2
  29. {
  30. public partial class Page : UserControl
  31. {
  32. public ObservableCollection<SomeClass> StringsParent { get; set; }
  33.  
  34. public Page()
  35. {
  36. InitializeComponent();
  37. StringsParent = new ObservableCollection<SomeClass>();
  38. ic.ItemsSource = StringsParent;
  39. }
  40.  
  41. private void Save(object sender, RoutedEventArgs e)
  42. {
  43. SomeClass c = new SomeClass();
  44. c.StringsChild.Add("First");
  45. c.StringsChild.Add("Second");
  46. c.StringsChild.SetSelectedItem("Second");
  47. StringsParent.Add(c);
  48. }
  49. }
  50.  
  51. public class SomeClass
  52. {
  53. public SelectableObservablecollection<string> StringsChild { get; set; }
  54.  
  55. public SomeClass()
  56. {
  57. StringsChild = new SelectableObservablecollection<string>();
  58. }
  59. }
  60.  
  61. public class SelectableObservablecollection<T> : ObservableCollection<T>
  62. {
  63. public SelectableObservablecollection()
  64. : base()
  65. {
  66.  
  67. }
  68.  
  69. public void SetSelectedItem<Q>(Q selectedItem)
  70. {
  71. foreach (T item in this)
  72. {
  73. if (item.Equals(selectedItem))
  74. {
  75. SelectedItem = item;
  76. return;
  77. }
  78. }
  79. }
  80.  
  81. private T _selectedItem;
  82. public T SelectedItem
  83. {
  84. get
  85. {
  86. return _selectedItem;
  87. }
  88. set
  89. {
  90. _selectedItem = value;
  91. OnPropertyChanged(new PropertyChangedEventArgs("SelectedItem"));
  92. }
  93. }
  94. }
  95. }
  96.  
  97. <DataTemplate x:Key="icTemplate">
  98. <ComboBox ItemsSource="{Binding StringsChild}"
  99. SelectedItem="{Binding StringsChild.SelectedItem}"/>
  100. </DataTemplate>
Add Comment
Please, Sign In to add comment