这可能是一个非常简单的问题,我仍然不知道如何解决这个问题。
我的MVVM应用程序中有一个模型,我想绑定到树视图。但是我只能将树视图绑定到项目列表(或者在我的例子中是ObservableCollection)。 这是我目前使用的模型:
/// <summary>
/// Represents an group a character can belong to.
/// </summary>
public class OrganisationBase : ModelBase<OrganisationBase>
{
/// <summary>
/// The name.
/// </summary>
private string name;
/// <summary>
/// The parent organization.
/// </summary>
private ObservableCollection<OrganisationBase> parentOrganizations;
/// <summary>
/// Gets or sets the name of the organization.
/// </summary>
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.NotifyPropertyChanged(p => p.Name);
}
}
/// <summary>
/// Gets or sets the parent organization.
/// </summary>
public ObservableCollection<OrganisationBase> ParentOrganizations
{
get
{
return this.parentOrganizations;
}
set
{
this.parentOrganizations = value;
this.NotifyPropertyChanged(p => p.ParentOrganizations);
}
}
}
现在我的问题是:如何在不使用Observable集合的情况下将此模型绑定到树视图。我想这样做,因为不需要ObservableCollection,因为每个组织只能有一个父。
或者,如何将以下代码绑定到树视图中:
/// <summary>
/// Represents an group a character can belong to.
/// </summary>
public class OrganisationBase : ModelBase<OrganisationBase>
{
/// <summary>
/// The name.
/// </summary>
private string name;
/// <summary>
/// The parent organization.
/// </summary>
private OrganisationBase parentOrganizations;
/// <summary>
/// Gets or sets the name of the organization.
/// </summary>
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.NotifyPropertyChanged(p => p.Name);
}
}
/// <summary>
/// Gets or sets the parent organization.
/// </summary>
public OrganisationBase ParentOrganizations
{
get
{
return this.parentOrganizations;
}
set
{
this.parentOrganizations = value;
this.NotifyPropertyChanged(p => p.ParentOrganizations);
}
}
}
这是我目前使用的树视图的代码:
<TreeView ItemsSource="{Binding Path=Character.CharacterAllegiances.MemberOf}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="True" />
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding ParentOrganizations}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
注意:Organization属性是角色模型的一部分。当我使用ObservableCollections时,一切都显示正常。但是如上所述,我想丢弃这个ObservableCollections。
问候 Ruhrpottpatriot
答案 0 :(得分:0)
TreeView期望一组项目以构建其节点,这显然是正确的方式,并且非常自我解释。
将树视图绑定到单个对象只有在该对象将其自身暴露为集合时才会起作用,例如实现IEnumerable
,树视图将使用IEnumerable
实现来填充数据。
或者你可以只针对对象绑定到一个集合,例如
<TreeView ItemsSource="{Binding object.SomeCollection}" />
答案 1 :(得分:0)
您需要使用HierarchicalDataTemplate。
要绑定数据(例如上面的文件夹和文件),您可以参考这篇文章: WPF Treeview: data binding of heterogeneous types of data using CompositeCollection class