简体   繁体   English

在WPF中以编程方式将comboBox添加到ListView

[英]Add comboBox to listview programmatically in wpf

i have a ListView in wpf 我在wpf中有一个ListView

<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. 第一列是文本,秒数是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 ? 为什么我的comboBox无法正确显示?

You should modify the ListView.itemTemplate property and add a data template. 您应该修改ListView.itemTemplate属性并添加数据模板。

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. 是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.. 除了只需要使用组合框而不是按钮并使用适当的绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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