我将数据类绑定到DataContext。数据类有家长的集合,每个家长都有孩子的集合。
问题很容易描述,如何在ListBox中显示所有儿童,而不显示父母?
这是我的样本课:
public class Data : ObservableCollection<Parent>
{
public Data()
{
Parent p1 = new Parent();
p1.ParenName = "A1";
p1.Childrens.Add(new Children
{
ChildrenName = "Children-1",
ChildrenCode = "A1-1"
});
p1.Childrens.Add(new Children
{
ChildrenName = "Children-2",
ChildrenCode = "A1-2"
});
Parent p2 = new Parent();
p2.ParenName = "A2";
p2.Childrens.Add(new Children
{
ChildrenName = "Children-3",
ChildrenCode = "A2-1"
});
p2.Childrens.Add(new Children
{
ChildrenName = "Children-4",
ChildrenCode = "A2-2"
});
this.Add(p1);
this.Add(p2);
}
}
public class Parent
{
public Parent()
{
this._childrens = new ObservableCollection<Children>();
}
string _parenName;
public string ParenName
{
get { return _parenName; }
set { _parenName = value; }
}
ObservableCollection<Children> _childrens;
public ObservableCollection<Children> Childrens
{
get { return _childrens; }
set { _childrens = value; }
}
}
public class Children
{
string _childrenName;
public string ChildrenName
{
get { return _childrenName; }
set { _childrenName = value; }
}
string _childrenCode;
public string ChildrenCode
{
get { return _childrenCode; }
set { _childrenCode = value; }
}
}和XAML:
<Window x:Class="ListBoxSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="ListBoxSample">
<Window.Resources>
<DataTemplate x:Key="parent">
<TextBlock Text="{Binding Path=ParentName}"></TextBlock>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source=Parent}" ItemTemplate="{StaticResource parent}"></ListBox>
</Grid>
</Window>
有人能告诉我怎么用HierahicalDataTemplate来做吗?
发布于 2013-12-01 17:40:28
HierachicalDataTemplate是给TreeView的。如果要在ListBox中显示它,请创建一个wrapper property containing flat list for children并将您的ListBox与该包装器属性绑定。
或
使用IValueConverter将您的集合扁平化,这将返回子集合列表。
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
var parentList = value as ObservableCollection<Parent>;
var childCollection = new ObservableCollection<Children>();
if (parentList != null)
{
childCollection = new ObservableCollection<Children>
(parentList.SelectMany(p => p.Childrens));
}
return childCollection;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
}XAML -
创建一个转换器实例,并使用它将其绑定到ItemsSource -
<ListBox ItemsSource="{Binding Source=Parent,
Converter={StaticResource MyConverter}}"
DisplayMemberPath="ChildrenName"/>https://stackoverflow.com/questions/20314863
复制相似问题