Это не очень легко сделать, потому что DataContext
из GroupItem
является экземпляром 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} />