首页 文章

在WPF中的ListView中填充ComboBox

提问于
浏览
3

我在 ListView 里面填了一个 ComboBox . 屏幕截图如下
enter image description here

如上所示,它显示“M”,“a”,“c”而不是“Mac” . 为什么将单词分成字符?

在我写的文件背后的代码中

ItemCategoryDAL itemCategoryDalObj = new ItemCategoryDAL();
            DataTable dataTable = itemCategoryDalObj.GetAllItemCategory();

            listView1.ItemsSource = dataTable.DefaultView;

在.xaml文件中我写道:

<ListView  Height="148" HorizontalAlignment="Left" Margin="23,12,0,0" Name="listView1" VerticalAlignment="Top" Width="447" >
  <ListView.View>
     <GridView>
        - - - - - - - - 
        - - - - - - - -
        <GridViewColumn Header="Category Name" Width="150">
           <GridViewColumn.CellTemplate>
               <DataTemplate>
                  <ComboBox ItemsSource="{Binding Path=IC_NAME }" Width="120" />
               </DataTemplate>
           </GridViewColumn.CellTemplate>
        </GridViewColumn> 
        - - - - - - - - -
        - - - - - - - - -
     </GridView>
  </ListView.View>
</ListView>

我正在使用Visual Studio 2010

dataTable 的屏幕截图,我用作ListView的 ItemSource . (在调试期间拍摄)
enter image description here

2 回答

  • 4

    ComboBox 允许用户从多个项目中进行选择 . 它通过迭代 ItemsSource 中的所有项目并将每个项目添加到其 Items 来填充自身 .

    您将 ItemsSource 设置为返回字符串的属性 . 由于字符串可以迭代, ComboBox 会自动填充它在迭代时获得的项目,因此字符串"Mac"将变为项目"M","a"和"c" .

    那是's why you'看到你所看到的 . 问题实际上是:你期望看到什么(或者你想看到什么)以及为什么? ComboBox 应显示哪些项目?如果您希望它显示 DataTable 中显示的所有类别名称,您可以执行以下操作:

    ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=ItemsSource}"
    

    然后使用 DataTemplate 从每个项目中拉出 IC_Name 列:

    <ComboBox.ItemTemplate>
       <DataTemplate>
          <TextBlock Text="{Binding IC_Name}"/>
       </DataTemplate>
    </ComboBox.ItemTemplate>
    

    请注意,这样做会遇到各种意外现象 . 例如,如果表中只有一行"Foo"为 IC_Name 的值,那么当用户为该行选择其他值并且表更新时,值"Foo"将从所有 ComboBox 消失,使其无法实现供用户撤消该更改 . 此外,如果五行包含"Foo",则每个 ComboBox 将在其下拉列表中显示"Foo"的所有五个实例 .

  • 0

    绑定似乎有效,IC_NAME存在并将“Mac”作为字符串返回 . 这将隐含地转换为具有三个条目的可枚举字符串:“M”,“a”和“c” . 这就是你的ComboBox的ItemsSource .

    <ComboBox ItemsSource="{Binding Path=IC_NAME }" Width="120" />
    

    可能它应该是这样的:

    <ComboBox 
      SelectedItem="{Binding Path=IC_NAME}"
      ItemsSource="{Binding Path=NameOfACollectionProperty }" 
      Width="120" />
    

相关问题