扩展器IsExpanded绑定

时间:2011-05-23 15:10:26

标签: c# .net wpf mvvm

在以下代码中:

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。

的类

因此,如果我手动打开其中一个扩展器,它应该将IsExpanded属性设置为该MyData的GroupNode的true。

1 个答案:

答案 0 :(得分:6)

这不是一件容易的事,因为DataContext的{​​{1}}是CollectionViewGroup的一个实例,而且这个类没有GroupItem属性。但是,您可以在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;
    }
}

在XAML中,只需按如下方式声明分组:

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
}

然后绑定<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