Let's pretend I have the following xaml...
<UserControl.Resources>
<local:ViewModel x:Name="viewModel" />
<local:LoadChildrenValueConverter x:Name="valueConverter" />
</UserControl.Resources>
<UserControl.DataContext>
<Binding Source="{StaticResource viewModel}" />
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" Background="White">
<control:TreeView ItemsSource="{Binding Root}">
<control:TreeView.ItemTemplate>
<control:HierarchicalDataTemplate ItemsSource="{Binding Converter={StaticResource valueConverter}}">
<TextBlock Text="{Binding}" />
</control:HierarchicalDataTemplate>
</control:TreeView.ItemTemplate>
</control:TreeView>
</Grid>
...and the following code to go with it...
using System; using System.Collections.ObjectModel; using System.Windows.Data; namespace SilverlightViewModelSpike { public class ViewModel { public ViewModel() { Root = new ObservableCollection() { "Item 1", "Item 2", "Item 3", }; } public ObservableCollection Root { get; private set; } } public class LoadChildrenValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return new ObservableCollection() { "Item 1", "Item 2", "Item 3", }; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
This works as expected, but it feels wrong that I have two separate classes that are required in order to grab the needed data for my view (imagine that ViewModel and LoadChildrenValueConverter pulled data from a web service instead of returning hard coded data). Is there a better solution here? I was thinking maybe something like this...
using System; using System.Collections.ObjectModel; using System.Windows.Data; namespace SilverlightViewModelSpike { public class ViewModel { public ViewModel() { Root = new ObservableCollection() { "Item 1", "Item 2", "Item 3", }; ValueConverter = new LoadChildrenValueConverter(); } public ObservableCollection Root { get; private set; } public LoadChildrenValueConverter ValueConverter { get; private set; } } public class LoadChildrenValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return new ObservableCollection() { "Item 1", "Item 2", "Item 3", }; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
... but then i can't get this line to work...
<control:HierarchicalDataTemplate ItemsSource="{???}"
>
...and even that doesn't seem like a great solution. Does anyone have a nice clean solution for this?