简体   繁体   English

列表框中两列数据绑定的麻烦

[英]Two column data binding in a listbox trouble

My understanding of DataBinding is still at the "working on it" level, so here is my issue. 我对DataBinding的理解仍处于“正在研究中”的水平,所以这是我的问题。 I have this data: 我有此数据:

private class User
    {
        public string username { get; set; }
        public string real_name { get; set; }
    }

ObservableCollection<User> users = new ObservableCollection<User>();
...adds stuff...
CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(users);

I want this to be displayed in a two column ListBox. 我希望将其显示在两列ListBox中。 I've gotten in in a two column ComboBox by doing: 我通过执行以下操作进入了两列ComboBox:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="114,23,0,0" Name="comboBox_client" VerticalAlignment="Top" Width="113" IsEditable="True" ItemsSource="{Binding}" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding username}" Name="left" Width="50" />
                    <TextBlock Text="{Binding real_name}" Name="right" Width="100" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

with

comboBox_client.ItemsSource = view;

But I'm not sure how to make the step over to a ListBox, since I see no ItemTemplate, and I don't understand the concept behind what the above Xaml is actually doing. 但是我不确定如何过渡到ListBox,因为我没有看到ItemTemplate,而且我不理解上述Xaml实际上在做什么的概念。 If I take out the ItemTemplate part and try the rest on the ListBox, I just just a listbox full of System.Windows.DataTemplate. 如果我取出ItemTemplate部分并尝试在ListBox上进行其余操作,那么我只是一个充满System.Windows.DataTemplate的列表框。

Point in the right direction please? 请指向正确的方向?

ListBox has an ItemTemplate property too. ListBox也具有ItemTemplate属性。 I think you just missed that. 我想你只是想念那个。

You can just use the same DataTemplate you used for your ComboBox . 您可以只使用与ComboBox相同的DataTemplate

ListBox: 列表框:

    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding username}" Width="50" />
                    <TextBlock Text="{Binding real_name}" Width="100" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

But it seems to me, ListView is more suitable for this task: 但在我看来,ListView更适合此任务:

    <ListView ItemsSource="{Binding}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="User name" DisplayMemberBinding="{Binding username}" Width="50" />
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding RealName}" Width="100" />
            </GridView>
        </ListView.View>
    </ListView>

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

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