简体   繁体   中英

How to access SelectedItem of ComboBox inside DataTemplate

I have following XAML:

<ItemsControl x:Name="TextComboPairItemsControl" Grid.Row="1" Grid.ColumnSpan="2"
                  ItemsSource="{Binding Path=AllHeaders.Fields}">
         <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>

                        <TextBlock x:Name="TextBlock1" Text="{Binding}"
                                   Grid.Column="0" Margin ="2"/>
                        <ComboBox x:Name="ComboBox1" ItemsSource="{Binding ElementName=MainGrid, Path=DataContext.Tags}"
                                  SelectedItem="{Binding ElementName=MainGrid, Path=DataContext.TextComboPairList.Combo}"
                                  Grid.Column="1" Margin ="2" SelectedIndex="0" IsEditable="True"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
    </ItemsControl>

Now, in my code I want to be able to read what the user has chosen in each ComboBox. For that I created a class:

public class TextComboPair
{
    public string TextContent { get; set; }
    public string ComboContent { get; set; }
}

Every pair of TextBlock and ComboBox would have its own object of the above class. I also created a list to store all those pairs of data:

public List<TextComboPair> TextComboPairList 
{
    get; 
    set; 
}

It is defined in my DataContext.

So, if, for example, there was displayed a list of three TextBlock-ComboBox pairs on the screen and user would choose what he needs in each ComboBox, I'd like to have the above List populated with that data.

As you can see in XAML I bound Selected Item to this List, but I must have done it wrong.

Hwo can I fix this?

Try this :

<ComboBox x:Name="ComboBox1" ItemsSource="{Binding  Path=DataContext.Tags, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl }}}"
                              SelectedItem="{Binding  RelativeSource={RelativeSource AncestorType={x:Type ItemsControl }}, Path=DataContext.TextComboPairList.Combo}"
                              Grid.Column="1" Margin ="2" SelectedIndex="0" IsEditable="True"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM