I'm having a problem implementing a search functionality in my TreeView on a WPF Project.
I used this guide to create a TreeView with ViewModels. I have used the TextSeachDemo and edited the Controls in a way that they that they fit my application. (Added the right Classes, more layers etc.)
Everything works fine, I get a structure with correct children and parents and the search function also works, as it finds the correct entry.
Problem now is: When i try to set the "IsExpanded" Property from code nothing happens. Debubgging shows me that the PropertyChanged event in the RaiseProperty Changed Method is always null.
In the test Project provided by Josh Smith, everything seems to be working fine. The only significant difference that i could make out is that he set the datacontext in code while i did in the XAML:
Code from Josh Smith:
public TextSearchDemoControl()
{
InitializeComponent();
// Get raw family tree data from a database.
Person rootPerson = Database.GetFamilyTree();
// Create UI-friendly wrappers around the
// raw data objects (i.e. the view-model).
_familyTree = new FamilyTreeViewModel(rootPerson);
// Let the UI bind to the view-model.
base.DataContext = _familyTree;
}
From the constructor from the MainViewModel (The ViewModel that handles the entire window)
List<FactoryItem> rootItems = _machineService.GetFactoryItems();
FactoryTree = new FactoryTreeViewModel(rootItems);
Where as FactoryTree is a public Observable Property which i bind the DataContext of the TreeView too (instead of in code as above):
<TreeView DataContext="{Binding FactoryTree}" ItemsSource="{Binding FirstGeneration}">
The other way around by the way, when i open a item via the GUI, the breakpoint on my property does trigger and raise an event.
Any ideas?
This solution addresses the problem in a more mvvm friendly way. A
UserControl
contains aTreeView
. It uses the typeYourViewModel
as data context. The view model contains a collection ofYourDomainType
which itself has a child collectionChildElements
of the same type.In xaml, the data is bound to the
ElementInViewModel
collection of the view model. In addition there is aHierarchicalDataTemplate
(which is appropriate for a tree view).The type
YourDomainType
contains propertiesIsExpanded
andIsSelected
which are bound to the respective properties of theTreeViewItem
in aStyle
. If you set these properties in your view model the tree view should react as expected (selecting or expanding the respectiveTreeViewItem
).I am aware that
IsExpanded
andIsSelected
do not belong to a DTO object.YourDomainType
is probably more a type for displaying data, but it could also wrap a DTO object stored in it.