如何将对象数据从Combobox绑定到ListBox

时间:2017-03-14 10:58:37

标签: wpf data-binding listbox

这是自定义对象:

public class FileItem
{
    public string Name { get; set; }
    public string Path { get; set; }
}

Collection

public ObservableCollection<FileItem> collection { get; set; }

Combobox

<ComboBox
    Name="cbCollection" 
    ItemsSource="{Binding interfaces}"/>

ListBox

    <ListBox 
        Name="lbCollection "
        ItemsSource="{Binding collection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

所以我的Combobox填充了我的object集合,我希望在我的ListBox中查看其所有属性。

目前:

  1. 我只能看到属性Name
  2. 我可以看到Combobox中的所有对象,而不仅仅是所选对象。

1 个答案:

答案 0 :(得分:0)

如果您想要查看的不仅仅是name属性,还需要扩展数据模板以包含其他属性。

如果要查看所选项目的属性,则应绑定到组合框的SelectedItem属性。实际上我认为你不想要一个ListBox,因为只有一个选定的项目。

这应该让你开始:

<ContentControl Content="{Binding ElementName=cbCollection, Path=SelectedItem}">
  <ContentControl.Resources>
    <DataTemplate DataType="{x:Type local:FileItem}">
      <TextBlock Text="{Binding Name}"/>
    </DataTemplate>
  </ContentControl.Resources>
</ContentControl>
相关问题