【发布时间】:2013-04-21 14:52:34
【问题描述】:
这可能是一个非常简单的问题,但我仍然不知道如何解决。
我的 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>
注意:组织属性是角色模型的一部分。仍然当我使用 ObservableCollections 时,一切都显示得很好。但是如上所述,我想丢弃这个 ObservableCollections。
问候 鲁尔波特爱国者
【问题讨论】: