扩展器IsExpanded绑定

问题描述

| 在下面的代码中: http://msdn.microsoft.com/en-us/library/ms754027.aspx 如何将IsExpanded绑定到对象的MyData列表,其中每个对象都具有IsExpanded属性
<Expander IsExpanded={Binding Path=IsExpanded,Mode=TwoWay} />
这行不通!
MyData is List<GroupNode>;
GroupNode是一个包含通知属性更改属性IsExpanded的类。 因此,如果我手动打开其中一个扩展器,则应将MyData \ GroupNode的IsExpanded属性设置为true。     

解决方法

这不是一件容易的事,因为
GroupItem
DataContext
CollectionViewGroup
的实例,并且此类没有
IsExpanded
属性。但是,您可以在
GroupDescription
中指定一个转换器,使您可以为组的\“ name \”返回一个自定义值(
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,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} />