在以下代码中:
http://msdn.microsoft.com/en-us/library/ms754027.aspx
如何将IsExpanded绑定到MyData对象列表,其中每个对象都具有IsExpanded属性?
<Expander IsExpanded={Binding Path=IsExpanded, Mode=TwoWay} />
Run Code Online (Sandbox Code Playgroud)
这不起作用!
MyData is List<GroupNode>;
Run Code Online (Sandbox Code Playgroud)
GroupNode是一个包含通知属性已更改属性IsExpanded的类.
因此,如果我手动打开其中一个扩展器,它应该将IsExpanded属性设置为该MyData的GroupNode的true.
这不是很容易做到,因为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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是转换器:
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
}
Run Code Online (Sandbox Code Playgroud)
在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>
Run Code Online (Sandbox Code Playgroud)
然后绑定IsExpanded属性:
<Expander IsExpanded={Binding Path=Name.IsExpanded} />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4315 次 |
| 最近记录: |