Search code examples
wpf-controlsbindingobservablecollectionitemscontrol

wpf calling particular array item from button


I have a Movie class with a Dim _characters = New ObservableCollection(of String)

In my MainWindow.vb i have,

Dim movies = New ObservableCollection(of Movie)
Me.parentG.DataContext = Me.movies

i want to add characters to the movie based on button click at runtime.
How can i get the particaular movie for which the character button was clicked?

MainWindow.xaml:-

  <Grid Name="parentG" >

   <ItemsControl ItemsSource="{Binding}">
     <ItemsControl.ItemTemplate>
       <DataTemplate>

       <Grid>
         <Grid.ColumnDefinitions>      
            <ColumnDefinition Width="100"></ColumnDefinition>
            <ColumnDefinition Width="100"></ColumnDefinition>
            <ColumnDefinition Width="700"></ColumnDefinition>
          </Grid.ColumnDefinitions>
           <TextBox Grid.Column="0" Text="{Binding MovieName}" />
       <Button Grid.Column="1" Content="New Character" Click="newCharacterButton_Click" Height="20" Width="100" HorizontalAlignment="Left" />

       <ListBox Grid.Column="2" Name="cList" ItemsSource="{Binding Characters}">  
           <ListBox.ItemTemplate >
             <DataTemplate >
               <TextBox Text="{Binding Name}"/>  
             </DataTemplate> 
            </ListBox.ItemTemplate>  
         </ListBox> 

        </Grid>

      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>

 </Grid>

Solution

  • finally figured it out. Below are the steps :-

    1. in the button handler, convert sender to Button
    2. get its parent, in my case it was the Grid
    3. Get the DataContext of the Grid, convert it to (in this case), Movie
    4. Get index of this Movie in the Movie array, assuming an index property existed for each Movie, and was set during initialization.
    5. Add a character to this movie