Haozhun
Haozhun

Reputation: 6521

ListBox inside ListBox, how do I know which button is clicked?

I have two ListBoxes, one inside another. And both ListBoxes will have items dynamically added into them upon user request.

Each time a button (not shown in the below code snippet) is clicked, a new item is added to the listbox. Each new item includes a new listbox and others.

And I have buttons inside the inner listbox, one for each list item of the inner listbox.

With DataContext, I can find the data binded to the inner list item, and make changes to it, so that changes are reflected on the proper list item.

However, I also need to make changes to the data binded to the outer list item, which corresponds to the button. How can I know which one it is?

I have came up with a solution, which I believe it not elegant enough. By making changes to the model, I can have each inner data holds a reference to the outer data, so that I can find the data binded to the outer list item. This doesn't seem like a proper solution though. Do you have any suggestions?


Below is code snippet of the xaml. I've simplified it, hope it's easy to understand. I feel you don't have to read the whole code.

<ListBox Name="QuestionsListBox" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}" >
    <ListBox.ItemTemplate>
    <DataTemplate>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <TextBox Text="{Binding Question, Mode=TwoWay}" Grid.Row="0" HorizontalAlignment="Stretch" TextWrapping="Wrap"/>
        <ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}">
            <ListBox.ItemTemplate>
            <DataTemplate>
            <Grid HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Button Grid.Column="0" Click="ChoiceAddButton_Click" Height="72" Width="72" HorizontalAlignment="Left" BorderBrush="Transparent">
                    <Button.Background>
                        <ImageBrush ImageSource="/Images/choices.add.png" Stretch="Fill" />
                    </Button.Background>
                </Button>
                <TextBox Text="{Binding Value, Mode=TwoWay}"  HorizontalAlignment="Stretch" Grid.Column="1" Margin="-20,0" />
            </Grid>
            </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
    </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 0

Views: 820

Answers (3)

Esoteric Screen Name
Esoteric Screen Name

Reputation: 6112

Why not just use QuestionsListBox.DataContext inside ChoiceAddButton_Click directly? You have a direct way to reference the outer ListBox from your code behind since you've given it a name, and DataContext is an accessible property.

    private void ChoiceAddButton_Click(object sender, RoutedEventArgs e)
    {
        ...
        var outerLBDataContext= QuestionsListBox.DataContext;
        ...
    }

This works fine for me in a demo solution using your provided XAML.

Edit 2:

Sorry, wasn't thinking. The Button's DataContext will be a Choice, not the Choices collection.

Your inner ListBox's DataContext is not a Question, it's Choices. Your outer TextBox has Question.Question as its DataContext. Binding Text or ItemsSource makes the DataContext point to the binding target. Here is a bit of tricky XAML to sneak in a DataContext reference.

Add an ElementName to your outer TextBox:

<TextBox Text="{Binding Question, Mode=TwoWay}" Grid.Row="0" HorizontalAlignment="Stretch" TextWrapping="Wrap" ElementName="questionTextBox"/> 

Now, add a hidden TextBlock inside your inner ListBox:

    <ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}"> 
        <ListBox.ItemTemplate> 
        <DataTemplate> 
        <Grid HorizontalAlignment="Stretch"> 
            <Grid.ColumnDefinitions> 
                <ColumnDefinition Width="Auto" /> 
                <ColumnDefinition Width="*" /> 
            </Grid.ColumnDefinitions> 
            <Button Grid.Column="0" Click="ChoiceAddButton_Click" Height="72" Width="72" HorizontalAlignment="Left" BorderBrush="Transparent"> 
                <Button.Background> 
                    <ImageBrush ImageSource="/Images/choices.add.png" Stretch="Fill" /> 
                </Button.Background> 
            </Button> 
            <TextBox Text="{Binding Value, Mode=TwoWay}"  HorizontalAlignment="Stretch" Grid.Column="1" Margin="-20,0" /> 
            <TextBlock Name="hiddenTextBlock" Visibility="Collapsed" DataContext="{Binding ElementName=questionTextBox, Path=DataContext}"
        </Grid> 
        </DataTemplate> 
        </ListBox.ItemTemplate> 
    </ListBox> 

Finally, inside your event handler, you can navigate around the tree to get that reference:

    private void ChoiceAddButton_Click(object sender, RoutedEventArgs e)
    {
        Button btn = sender as Button;
        if(btn == null) return; //won't happen when this method handles the event
        Grid g = btn.Parent as Grid;
        if(g!=null) // also unlikely to fail
        {
           TextBlock tb = g.FindName("hiddenTextBlock") as TextBlock;
           if(tb!=null) // also unlikely to fail, but never hurts to be cautious
           {
               var currentQuestion = tb.DataContext;
               // now you've got the DC you want
           }
        }
    }

I'd like to note that this isn't really an elegant solution. It is an all UI solution, however, which could be a useful thing. But better design would be to include Parent references in your Choice and ChoiceList (or whatever they're called) classes and use that. Then it would be as simple as calling btn.DataContext.Parent.Parent with appropriate type conversions. This way your code becomes easier to read and maintain.

Upvotes: 1

Santhu
Santhu

Reputation: 1525

Is this necessary to use the Button control in your solution ?? If not fixed, then you can use the "Image control" as specified below <Image Source="/Images/choices.add.png" Height="72" Width="72" HorizontalAlignment="Left" Stretch="Fill"/>

If you use the Image control then in combination with this you can add the selection changed event to inner list box ( ChoicesListBox). Then in the Handler you can get the item selected as it comes as parameter with the selection changed event(SelectionChangedEventArgs).

Modify the List box and add the Selection changed event handler as below

<ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}" SelectionChanged="Items_SelectionChanged">

in page.xaml.cs you can add the handler and access the item as follows

private void Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {           
            if (e.AddedItems[0] != null)
            {
//Please use the casting to the Choices items type to make use. 
                var temp = (ChoicesItemViewModel)e.AddedItems[0];
            }
    }

Upvotes: 0

jes
jes

Reputation: 331

You could add an event to your inner model that your containing datamodel subscribes to before adding it to the 'Choices' collection and pass the relevant information that way.

Upvotes: 0

Related Questions