这不是很容易做到,因为GroupItem 的DataContext 是CollectionViewGroup 的一个实例,而这个类没有IsExpanded 属性。但是,您可以在GroupDescription 中指定一个转换器,从而允许您为组的“名称”返回一个自定义值(CollectionViewGroup.Name 属性)。这个“名字”可以是任何东西;在您的情况下,您需要它是一个包含组名(例如分组键)并具有 IsExpanded 属性的类:
这是一个例子:
public class ExpandableGroupName : INotifyPropertyChanged
{
private object _name;
public object Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
private bool? _isExpanded = false;
public bool? IsExpanded
{
get { return _isExpanded; }
set
{
if (_isExpanded != value)
{
_isExpanded = value;
OnPropertyChanged("IsExpanded");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
public override bool Equals(object obj)
{
return object.Equals(obj, _name);
}
public override int GetHashCode()
{
return _name != null ? _name.GetHashCode() : 0;
}
public override string ToString()
{
return _name != null ? _name.ToString() : string.Empty;
}
}
这是转换器:
public class ExpandableGroupNameConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return new ExpandableGroupName { Name = value };
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var groupName = value as ExpandableGroupName;
if (groupName != null)
return groupName.Name;
return Binding.DoNothing;
}
#endregion
}
在 XAML 中,只需将分组声明如下:
<my:ExpandableGroupNameConverter x:Key="groupConverter" />
<CollectionViewSource x:Key='src'
Source="{Binding Source={StaticResource MyData},
XPath=Item}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="@Catalog" Converter="{StaticResource groupConverter}" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
然后像这样绑定IsExpanded 属性:
<Expander IsExpanded={Binding Path=Name.IsExpanded} />