0

我是 WPF 的新手... :)

我需要 ListBox 来显示分组项目,什么效果很好。

    <ListBox Width="120" Loaded="ListBox_Loaded" SelectionChanged="ListBox_SelectionChanged" >
        <ListBox.GroupStyle>
            <GroupStyle />
        </ListBox.GroupStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ListBox ItemsSource="{Binding Items}" BorderThickness="0" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

但是在 *ListBox_SelectionChanged* SelectedIndex 仍然是 -1 并且 SelectedItems 集合也是空的。

下面是一段代码:

        public ICollectionView Groups()
    {
        List<Groups> groups = new List<AC.Groups>();
        groups.Add(new AC.Groups { Items = Properties.Settings.Default.Worker, Name="Worker" });
        groups.Add(new AC.Groups { Items = Properties.Settings.Default.Flow, Name = "Flow" });

        ICollectionView groups = CollectionViewSource.GetDefaultView(groups);
        groups.GroupDescriptions.Add(new PropertyGroupDescription("Name"));

        return groups;
    }

    private void ListBox_Loaded(object sender, RoutedEventArgs e)
    {
        (sender as ListBox).ItemsSource = Groups();
    }

    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show((sender as ListBox).SelectedIndex.ToString());
    }

    class Groups
    {
        public System.Collections.Specialized.StringCollection Items { get; set; }
        public string Name { get; set; }

        public override string ToString()
        {
            return Name;
        }
    }

谢谢你的帮助!

4

1 回答 1

1
<DataTemplate>
    <ListBox ItemsSource="{Binding Items}" BorderThickness="1" SelectionChanged="ListBox_SelectionChanged" />
</DataTemplate>

错位的事件处理程序... :)

于 2013-06-25T07:26:05.433 回答