简体   繁体   中英

How to bind Observablecollection<T> with combobox in wpf

I am trying to bind Observablecollection<T> with ComboBox . ComboBox having Datatemplete

<ComboBox Width="150" Margin="20,0,0,5" Name="cbSelection" Height="20" 
              BorderThickness="2" BorderBrush="Black" 
              SelectedIndex="0" DataContext="{Binding AdComboBox}">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="1*"/>
                                <ColumnDefinition Width="1*"/>
                                <ColumnDefinition Width="1*"/>
                            </Grid.ColumnDefinitions>
                            <TextBlock Grid.Column="0" Text="{Binding XPath=LOC, Mode=OneWay}" Margin="5,0,5,0"/>
                            <TextBlock Grid.Column="1" Text="{Binding XPath=PUB, Mode=OneWay}" Margin="0,0,5,0"/>
                            <TextBlock Grid.Column="2" Text="{Binding XPath=EDI, Mode=OneWay}" Margin="0,0,5,0"/>
                        </Grid>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

but not get the data in ComboBox what going wrong thanks in advance

Use the ItemsSource of the ComboBox to point to the ObservableCollection<T> . Also: Use Path, not XPath which is used for binding to XML documents.

<ComboBox Width="150" Margin="20,0,0,5" Name="cbSelection" Height="20" 
          BorderThickness="2" BorderBrush="Black" 
          ItemsSource="{Binding AdComboBox}"
          SelectedIndex="0">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="1*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" 
                           Text="{Binding Path=LOC, Mode=OneWay}"
                           Margin="5,0,5,0"/>
                <TextBlock Grid.Column="1" 
                           Text="{Binding Path=PUB, Mode=OneWay}"
                           Margin="0,0,5,0"/>
                <TextBlock Grid.Column="2" 
                           Text="{Binding Path=EDI, Mode=OneWay}"
                           Margin="0,0,5,0"/>
            </Grid>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Side note: you might want to rename the collection to something more functional instead of AdComboBox . Eg, Ads Because it is not a ComboBox but it is a collection of Ads(?)

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