0

I'm using a TreeView with HierarchicalDataTemplate but can't get the IsExpanded property working for higher levels than the first. Here's my xaml:

<TreeView>
     <TreeView.ItemTemplate>
         <HierarchicalDataTemplate ItemsSource="{Binding Children}">
             <TextBlock Text="{Binding Text}" />
         </HierarchicalDataTemplate>
     </TreeView.ItemTemplate>
</TreeView>

In my ResourceDictionary I have:

<Style TargetType="TreeViewItem">
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
</Style>

what makes the first order work.

In higher indention levels IsExpanded is always false because the PropertyChangedEventHandler is not fired for children.

Here's my class:

public class ListItem : INotifyPropertyChanged
{
    private bool isExpanded;
    public bool IsExpanded
    {
        get { return isExpanded; }
        set
        {
            if (isExpanded != value)
            {
                isExpanded = value;
                SendPropertyChanged("IsExpanded");
            }
        }
    }
    private void SendPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<ListItem> Children { get; set; }
    ...
}

EDIT: I'm very sorry, my corrected code is working!

4

1 回答 1

0

如果您想自动扩展所有子项以及目标项,那么您需要自己向下传播更改,请执行以下操作....

public bool IsExpanded 
{ 
    get { return isExpanded; } 

    set 
    { 
        if (isExpanded != value) 
        { 
            isExpanded = value; 
            if (isExpanded)
            {
                foreach(ListItem child in Children)
                    child.IsExpanded = true;
            }
            SendPropertyChanged("IsExpanded"); 
        } 
    } 
} 
于 2011-12-19T04:44:39.733 回答