我有以下代码。
我的TreeViewItem:
class ComponenteNodoViewModel : BaseViewModel
{
public string Nombre { get; set; }
private List<ComponenteNodoViewModel> _children;
private bool _isExpanded;
private bool _isSelected;
public ComponenteNodoViewModel Parent { get; set; }
public bool IsExpanded
{
get { return _isExpanded; }
set
{
_isExpanded = value;
base.RaisePropertyChangedEvent("IsExpanded");
}
}
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
base.RaisePropertyChangedEvent("IsSelected");
}
}
public List<ComponenteNodoViewModel> Children
{
get { return _children; }
set { _children = value; }
}
}
我拥有treeView的视图的ViewModel。我在GUI中有更多的元素,也有一些底部等等,但我只把与treeView有关系的代码放在一起。
public List<ComponenteNodoViewModel> ComponenteJerarquia { get; private set; }
...
private void componenteJerarquiaConstruirArbol(List<vComponentesEstructuras> paramNodos)
{
List<ComponenteNodoViewModel> misNodos = new List<ComponenteNodoViewModel>();
ComponenteNodoViewModel miNodo = new ComponenteNodoViewModel();
miNodo.Nombre = "Prueba";
misNodos.Add(miNodo);
ComponenteJerarquia = new List<ComponenteNodoViewModel>(misNodos);
}
最后我的观点是:
<UserControl x:Class="GTS.CMMS.Client.Views.ucMaquinasPrincipalView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
xmlns:ViewModels="clr-namespace:Project.ViewModel"
mc:Ignorable="d" d:DesignHeight="800" d:DesignWidth="1000">
<Grid>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="232" />
<ColumnDefinition Width="757" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="309*" />
<RowDefinition Height="350*" />
</Grid.RowDefinitions>
<TreeView ItemsSource="{Binding ComponenteJerarquia}" Margin="6,6,8,5" Name="trvComponente" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<HierarchicalDataTemplate DataType="{x:Type ViewModels:ComponenteNodoViewModel}" ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Nombre}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type ViewModels:ComponenteNodoViewModel}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Nombre}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView>
</Grid>
</Grid>
</UserControl>
问题在于,当我调用componenteJerarquiaConstruirArbol方法时,不会填充树视图。
我认为问题是绑定,但我看不出问题。
答案 0 :(得分:1)
属性ComponenteJerarquia
只是一个普通属性,因此当您设置它时,绑定系统不会被通知它需要更新绑定。您需要在该类中实现INotifyPropertyChanged
并在setter中引发PropertyChanged
事件。
好吧,另一部分是你不应该将你的HierarchicalDataTemplates放在TreeView中 - 这使得它认为你正试图将它们放在实际的树中。而是将这些模板移到您的资源中。