我是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;
}
}
谢谢你的帮助!
答案 0 :(得分:1)
<DataTemplate>
<ListBox ItemsSource="{Binding Items}" BorderThickness="1" SelectionChanged="ListBox_SelectionChanged" />
</DataTemplate>
错放的事件处理程序......:)