Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>UPDATE</strong><br> Figured out a much better way to do this. This will also account for changes in the ObservableCollection. </p> <p>The Xaml can just look like this</p> <pre><code>&lt;Window.Resources&gt; &lt;HierarchicalDataTemplate x:Key="Level1" ItemsSource="{Binding Path=Childs}"&gt; &lt;TextBlock Text="{Binding Path=Name}"/&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/Window.Resources&gt; &lt;TreeView ItemsSource="{Binding}" ...&gt; &lt;TreeView.ItemContainerStyle&gt; &lt;Style TargetType="{x:Type TreeViewItem}"&gt; &lt;Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" /&gt; &lt;Setter Property="IsExpanded" Value="{Binding Path=IsExpanded, Mode=TwoWay}" /&gt; &lt;/Style&gt; &lt;/TreeView.ItemContainerStyle&gt; &lt;/TreeView&gt; </code></pre> <p>And then we handle the IsSelected Property in the Model/ViewModel instead.</p> <pre><code>public class MyViewModel : INotifyPropertyChanged { private static MyViewModel s_lastSelectedTestItem = null; public MyViewModel(string name) { Name = name; m_isSelected = false; Childs = new ObservableCollection&lt;MyViewModel&gt;(); Childs.CollectionChanged += new NotifyCollectionChangedEventHandler(TestItems_CollectionChanged); } void TestItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (IsSelected == true &amp;&amp; Childs.Count &gt; 0) { Childs[0].IsSelected = true; IsExpanded = true; } } public string Name { get; set; } public ObservableCollection&lt;MyViewModel&gt; Childs { get; set; } private bool m_isSelected; public bool IsSelected { get { return m_isSelected; } set { m_isSelected = value; if (m_isSelected == true) { if (s_lastSelectedTestItem != null) { s_lastSelectedTestItem.IsSelected = false; } s_lastSelectedTestItem = this; if (Childs.Count &gt; 0) { IsExpanded = true; Childs[0].IsSelected = true; m_isSelected = false; } } OnPropertyChanged("IsSelected"); } } private bool m_isExpaned; public bool IsExpanded { get { return m_isExpaned; } set { m_isExpaned = value; OnPropertyChanged("IsExpanded"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload