简体   繁体   中英

Add comboBox to listview programmatically in wpf

i have a ListView in wpf

<ListView Name="listArea">
    <ListView.View>
        <GridView>
            <GridViewColumn x:Name="colName" Header="نام تحویلدار" Width="150" DisplayMemberBinding="{Binding Path=name}"/>
            <GridViewColumn x:Name="colComboBox" Header="منطقه" Width="120" DisplayMemberBinding="{Binding Path=cb}"/>
            </GridView>
     </ListView.View>
 </ListView>

i want add item to listview. first column is text and secound is comboBox.

foreach(personel ptahvildar in STATICS.db.personels.Where(q=>q.postCode==2))
{
    ListViewItem item = new ListViewItem();
    ComboBox cbox = new ComboBox();
    cbox.ItemsSource = STATICS.db.personels.Where(q => q.postCode == 2);
    cbox.DisplayMemberPath = "name";
    cbox.SelectedItem = ptahvildar;
    item.Content = new { name = ptahvildar.name, cb = cbox };
    listArea.Items.Add(item);
}

but the result is like this

结果

why my comboBox not show correctly ?

You should modify the ListView.itemTemplate property and add a data template.

Using an item template with data template you can add checkboxes, comboboxes, textboxes, buttons, etc. for every line item in your list view. Here is an example from an answer here in SO.

<ListView ItemsSource="{Binding Links}" x:Name="ListView1">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Border>
                    <Button Command="{Binding ElementName=ListView1, Path=DataContext.GetOddsCommand}" CommandParameter="{Binding}">
                         <TextBlock Text="{Binding}" />
                    </Button>
                </Border>
            </DataTemplate>
        </ListView.ItemTemplate> 
</ListView>

Except you only have to use a combobox instead of a button and use proper bindings..

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