Design time data for datatemplate in xaml - wpf

This may be a stupid question, but is it possible to define some sample data as DataContext in order to see my DataTemplate in DesignView?
At the moment I always have to run my application to see whether my changes are working.
E.g. with the following code DesignView just shows an empty list box:
<ListBox x:Name="standardLayoutListBox" ItemsSource="{Binding myListboxItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Column="0" Content="{Binding text1}" />
<Label Grid.Column="1" Content="{Binding text2}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

public class MyMockClass
{
public MyMockClass()
{
MyListBoxItems.Add(new MyDataClass() { text1 = "test text 1", text2 = "test text 2" });
MyListBoxItems.Add(new MyDataClass() { text1 = "test text 3", text2 = "test text 4" });
}
public ObservableCollection<MyDataClass> MyListBoxItems { get; set; }
}
public class MyDataClass
{
public string text1 { get; set; }
public string text2 { get; set; }
}
In Your XAML
Add the namespace declaration
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Add the mock data context to window/control resources
<UserControl.Resources>
<local:MyMockClass x:Key="DesignViewModel"/>
</UserControl.Resources>
Then Modify Your ListBox to Reference the design time object
<ListBox x:Name="standardLayoutListBox"
d:DataContext="{Binding Source={StaticResource DesignViewModel}}"
ItemsSource="{Binding MyListBoxItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Column="0" Content="{Binding text1}" />
<Label Grid.Column="1" Content="{Binding text2}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Wen you are in the designer you should not have to mess with the view models therefore I think it's bet to include design time data in xaml and not in c#, have a look at this simple POCO representation
<ListView ItemsSource="{Binding Items}">
<d:ListView.ItemsSource>
<x:Array Type="{x:Type models:Monkey}">
<models:Monkey Name="Baboon" Location="Africa and Asia"/>
<models:Monkey Name="Capuchin Monkey" Location="Central and South America"/>
<models:Monkey Name="Blue Monkey" Location="Central and East Africa"/>
</x:Array>
</d:ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Monkey">
<TextCell Text="{Binding Name}"
Detail="{Binding Location}" />
</DataTemplate>
</ListView.ItemTemplate>

Related

Data binding in TreeViewItem (HierachicalDataTemplate)

I have a tree view nicely connected to my model with a MVVM pattern. I'm running into an issue with the context menu. I do not know how to bind to an element outside the tree. I have created a sample that demonstrates what I'm trying. I hope someone explain to me what I'm doing wrong.
In the sample I have five TextBlocks in the header, each binding differently to the data. And I have a context menu with five entries, again binding differently. The commentary says which binding works and which doesn't. There's even a difference between the header and the context menu.
Some bindings try to bind to another element in the UI another to a property in the view model.
Here's the XAML:
<Window x:Class="WpfApp7_TreeView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp7_TreeView"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800"
x:Name="root">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding SomeProperty}" /> <!-- ok -->
<TextBlock Grid.Row="1" Text="Text from XAML" x:Name="tb" /> <!-- ok -->
<TreeView Grid.Row="2" HorizontalAlignment="Stretch" ItemsSource="{Binding Departments}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Department}">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5" Text="{Binding DepartmentName }" /> <!-- ok -->
<TextBlock Margin="5" Text="{Binding ElementName=tb, Path=Text}"/> <!-- ok -->
<TextBlock Margin="5" Text="{Binding SomeProperty}"/> <!-- no show -->
<TextBlock Margin="5" Text="{Binding ElementName=root, Path=DataContext.SomeProperty}"/> <!-- ok -->
<TextBlock Margin="5" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window},
Path=DataContext.SomeProperty}"/> <!-- ok -->
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Some command" /> <!-- ok -->
<MenuItem Header="{Binding ElementName=tb, Path=Text}" /> <!-- no show -->
<MenuItem Header="{Binding SomeProperty}" /> <!-- no show -->
<MenuItem Header="{Binding ElementName=root, Path=DataContext.SomeProperty}"/> <!-- no show -->
<MenuItem Header="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window},
Path=DataContext.SomeProperty}" /> <!-- no show -->
</ContextMenu>
</StackPanel.ContextMenu>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
And here's the view model:
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace WpfApp7_TreeView
{
public class MainWindowViewModel : ViewModelBase
{
private string someProperty = "Text from the viewmodel";
public string SomeProperty
{
get { return someProperty; }
set { someProperty = value; OnPropertyChanged("SomeProperty"); }
}
public MainWindowViewModel()
{
Departments = new List<Department>()
{
new Department("Department 1"),
new Department("Department 2")
};
}
private List<Department> departments;
public List<Department> Departments
{
get {return departments; }
set { departments = value; OnPropertyChanged("Departments"); }
}
}
public class Department : ViewModelBase
{
public Department(string depname)
{
DepartmentName = depname;
}
public string DepartmentName { get; set; }
}
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propname));
}
}
}
}
TreeViewItem DataContexts get set to their list item, so the SomeProperty binding in the parent HierarchicalDataTemplate needs to use a RelativeSource binding instead. Change this:
<TextBlock Margin="5" Text="{Binding SomeProperty}"/> <!-- no show -->
... to this:
<TextBlock Margin="5" Text="{Binding DataContext.SomeProperty, RelativeSource={RelativeSource AncestorType=TreeView}}"/>
With respect to your ContextMenu, you are correct in noting that bindings have to be part of the visual tree. The solution to this is to bind via an intermediate Binding Proxy instead. Generally speaking you would bind to the parents DataContext, rather than directly to another control, but it can be done both ways:
<TreeView Grid.Row="2" HorizontalAlignment="Stretch" ItemsSource="{Binding Departments}">
<TreeView.Resources>
<local:BindingProxy x:Key="TextBlockProxy" Data="{Binding Text, ElementName=tb}" />
<local:BindingProxy x:Key="MainViewModelProxy" Data="{Binding}" />
</TreeView.Resources>
<TreeView.ItemTemplate>
...etc...
And then in the ContextMenu:
<!-- Binds to the TextBlock's Text property -->
<MenuItem Header="{Binding Data, Source={StaticResource TextBlockProxy}}" />
<!-- Binds to the main view model's SomeProperty -->
<MenuItem Header="{Binding Data.SomeProperty, Source={StaticResource MainViewModelProxy}}" />

WPF Databinding not working in both directions when DataGrid bound to Observable Collection of Properties with Sub properties

Excuse the wordy title, I'm having trouble with a succinct description. If I could come up with one, I could probably Google the right answer!
I am binding my DataGrid to an ObservableCollection of properties that themselves have properties. My grid is populated just fine, but when I edit the grid the changes are not getting back to my model.
I have an ObservableCollection
Normally, you'd just have some properties of MarriedCoupleRow, but I actually have something slightly more complicated. Each MarriedCoupleRow has some propties (Male, Female) which in turn expose properties (Height, Weight, Information). It's this Information that can be edited. Again, I can populate the grid just fine, but the setter property of Information is not hit when you edit the cell and tab off (or leave).
I'd appreciate any pointers or references, including how to better word my title!
Here's the simple code:
public class XMLDemoViewModel : ViewModelBase
{
public XMLDemoViewModel()
{
_rows = new ObservableCollection<MarriedCoupleRow>();
// create some data....
for (uint i = 0; i < 2;i++)
{
MarriedCoupleRow row = new MarriedCoupleRow();
row.Male = new HumanData();
row.Male.Height = (70 + i*5).ToString();
row.Male.Weight = 150+(i*30+1);
row.Male.Information = row.Male.Height + " " + row.Male.Weight;
row.Female = new HumanData();
row.Female.Height = (60 +i*3).ToString();
row.Female.Weight = 120+(i*10+5);
row.Female.Information = row.Female.Height + " " + row.Female.Weight;
_rows.Add(row);
}
}
#region Fields
private ObservableCollection<MarriedCoupleRow> _rows = null;
#endregion Fields
#region Properties
public ObservableCollection<MarriedCoupleRow> Rows
{
get
{
return _rows;
}
}
#endregion Properties
#region Commands
#endregion Commands
#region Private Methods
#endregion Private Methods
}
public class MarriedCoupleRow : ViewModelBase
{
private HumanData _Male = null;
public HumanData Male
{
get { return _Male; }
set
{
if (value != _Male)
{
_Male = value;
OnPropertyChanged("Male");
}
}
}
public HumanData Female { get; set; }
}
public class HumanData : INotifyPropertyChanged
{
public string Height { get; set; }
public uint Weight { get; set; }
private string _friendlyName;
public string Information
{
get
{
return _friendlyName;
}
set
{
if (_friendlyName != value)
{
_friendlyName = value;
OnPropertyChanged("Information");
}
}
}
}
And here's the XAML:
<Window x:Class="XMLDemo.Views.XMLDemoView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="XMLDemoView" Height="600" Width="1152">
<DockPanel>
<StackPanel Orientation="Horizontal" Height="120" DockPanel.Dock="Bottom">
<StackPanel Orientation="Horizontal">
<GroupBox Width="249" BorderThickness="2" Height="90">
<GroupBox.Header>
<TextBlock FontSize="12" FontWeight="Bold">Control</TextBlock>
</GroupBox.Header>
<Grid Height="64" Width="223">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0.5*"/>
<RowDefinition Height="0.5*"/>
</Grid.RowDefinitions>
</Grid>
</GroupBox>
</StackPanel>
</StackPanel>
<DataGrid ItemsSource="{Binding Path=Rows, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate >
<DataTemplate>
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Male" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Male.Height}" IsEnabled="False" Grid.Row="0"></TextBox>
<TextBox Text="{Binding Male.Weight}" IsEnabled="False" Grid.Row="1"></TextBox>
<TextBox Text="{Binding Male.Information, Mode=TwoWay}" Grid.Row="2"></TextBox>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate >
<DataTemplate>
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Female" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid >
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Female.Height}" IsEnabled="False" Grid.Row="0"></TextBox>
<TextBox Text="{Binding Female.Weight}" IsEnabled="False" Grid.Row="1"></TextBox>
<TextBox Text="{Binding Female.Information}" Grid.Row="2"></TextBox>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
Your TextBox.Text bindings need to be set to updatesource on propertychanged.
<TextBox Text="{Binding Male.Information, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2"></TextBox>
There must be something goofy going on with LostFocus which is the default. I tested this using your code.
I Like your post. As I seen from the coding you are using Complex property binding with DataGrid. Also complex property changes won't be reflect in DataGrid.
However you can achieve this requirement in sample level. I will try to make the sample and let you know.
Regards,
Riyaj Ahamed I

WPF/XAML using TreeViewItems in a TreeView with Databinding and advanced templates

I'm pretty new to XAML and to databinding, so hopefully this will be an easy question to someone out there...
I'm trying to build a TreeView using data binding that has a structure similar to this:
Category
Item Name
Item Name
Category
Item Name
So far, so good--I can do that. Next, I want to be able to expand the Item node and show details about that item. This works fine when I build the tree manually in the code-behind, but I want to use data binding instead. I ALMOST have this working, but as it is now, either I can't select the node OR I can't get the node to behave like a TreeViewItem where it shows just the item name when it is collapsed and can expand to show more--in my case a custom defined grid with data on it.
Here's a simplified sample of my XAML code:
<DataTemplate x:Key="ItemDataTemplate">
<TreeViewItem Header="{Binding Path=ItemName}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Price" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Price}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Description" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="Qty on Hand" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Qty}"/>
</Grid>
</TreeViewItem>
</DataTemplate>
<HierarchicalDataTemplate x:Key="CategoryDataTemplate" ItemsSource="{Binding Path=Categories}" ItemTemplate="{StaticResource ItemDataTemplate}">
<TextBlock Text="{Binding Path=CategoryName}"/>
</HierarchicalDataTemplate>
Based on this simplified example, the object that was defined in the code-behind would be something like this:
public class Category
{
public ObservableCollection<Item> Items {get; private set;}
public string CategoryName { get; set; }
//constructor and methods here
}
public class Item
{
public string ItemName {get; private set;}
public decimal Price { get; private set; }
public string Description {get; private set; }
public int Qty {get; set;}
//constructor and methods here
}
After reading this question and answer on stackoverflow, I can see that you cannot have your template be a TreeViewItem if you want to select the node. I tried getting rid of the TreeViewItem tag and going straight to the Grid which allows me to select the node, but now I can't collapse the node down to just the ItemName (header text).
I feel like it's darn close... what am I missing?
So, what you want is to make an Item look like it has more child nodes, even though its only "child" is itself, presented with more info?
Well, the most correct way of doing that might be to use an expander in ItemDataTemplate, like so:
<DataTemplate x:Key="ItemDataTemplate">
<Expander Header="{Binding Path=ItemName}" >
<Grid>
<Grid.ColumnDefinitions>
...
<Grid.RowDefinitions>
...
<TextBlock Grid.Row="0" Grid.Column="0" Text="Price" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Price}"/>
<TextBlock ...
</Grid>
</TreeViewItem>
</DataTemplate>
The expander doesn't look exactly like a standard TreeViewItem, but that can be fixed by making your own Template for the Expander.
Now, a slightly more hacky way of doing it would be to have a list of Items in the Item class, where each Item exposes itself as the only list element. Then, ItemDataTemplate would need to be a HierarchicalDataTemplate which referenced another, more detailed, "ItemDetailsTemlate":
public class Item
{
...
public List<Item> InfoWrapper
{
get { return new List<Item>() { this }; }
}
}
Xaml:
<DataTemplate x:Key="ItemDetailsTemplate">
<Grid>
<Grid.ColumnDefinitions>
...
<Grid.RowDefinitions>
...
<TextBlock Grid.Row="0" Grid.Column="0" Text="Price" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Price}"/>
<TextBlock ...
</Grid>
</DataTemplate>
<HierarchicalDataTemplate x:Key="ItemDataTemplate" ItemsSource="{Binding Path=InfoWrapper}" ItemTemplate="{StaticResource ItemDetailsTemplate}" >
<TextBlock Text="{Binding Path=ItemName}"/>
</HierarchicalDataTemplate>

listBox DataTemplate not picking up values

I am learning to use listBox in WPF with dataTemplate using the examples from MSDN, I can render a listBox bound to an ObservableCollection as a source and by overriding the ToString method.
However, I need to render an image and some texblocks for every item. Here's my XAML:
<Grid x:Class="MyAddin.WPFControls"
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:c="clr-namespace:MyAddin"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Background="Transparent"
HorizontalAlignment="Stretch" Width="auto"
Height="215" VerticalAlignment="Stretch" ShowGridLines="False">
<Grid.Resources>
<c:People x:Key="MyFriends"/>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock HorizontalAlignment="Left"
IsManipulationEnabled="True"
Height="20" Width="300">Activity Feed</TextBlock>
<ListBox Grid.Row="1" Name="listBox1" IsSynchronizedWithCurrentItem="True"
BorderThickness="0" ScrollViewer.VerticalScrollBarVisibility="Auto"
VerticalContentAlignment="Stretch" Margin="0,0,0,5" Background="Transparent">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Margin="5" BorderBrush="Black" BorderThickness="1">
<Image Source="{Binding Path=Avatar}" Stretch="Fill" Width="50" Height="50" />
</Border>
<StackPanel Grid.Column="1" Margin="5">
<StackPanel Orientation="Horizontal" TextBlock.FontWeight="Bold" >
<TextBlock Text="{Binding Path=Firstname }" />
</StackPanel>
<TextBlock Text="{Binding Path=Comment}" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
My Collection class is as following:
public class People : ObservableCollection<Person>
{ }
public class Person
{
private string firstName;
private string comment;
private Bitmap avatar;
public Person(string first, string comment, Bitmap avatar)
{
this.firstName = first;
this.comment = comment;
this.avatar = avatar;
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string Comment
{
get { return comment; }
set { comment = value; }
}
public Bitmap Avatar
{
get { return avatar;}
set { avatar = value; }
}
public override string ToString()
{
return firstName.ToString();
}
}
Once my addin is loaded, I am downloading my data and setting the itemsSource.
People p = new People();
p.Add(new Person("Willa", "Some Comment", myAvatar));
p.Add(new Person("Isak", "Some Comment", myAvatar));
p.Add(new Person("Victor", "Some Comment", myAvatar));
this.wpfControl.listBox1.ItemsSource = p;
The problem I am facing is that the items are being rendered as empty rows whereas If I remove the dataTemplate, the items are rendered fine with their firstName.
Don't see anything wrong with the bindings themselves, but your avatar type seems off, WPF expects ImageSource (i do not know if there is any implicit convertion between Bitmap and ImageSource, check for binding errors to find out).

WPF Treeview - Binding to a collection with different depths, and styling differently

Apologies for the long post -- Read a few threads about this, but still find it hard to implement. Basically, I have a collection of objects, defined as:
public class LibData
{
public string Name { get; set; }
ObservableCollection<LibObject> _list;
public ObservableCollection<LibObject> List { get { return _list; } }
public LibData(string name, LibDataType type)
{
this.Name = name;
_list = new ObservableCollection<LibObject>();
}
}
and the object:
public class LibObject
{
public string Name { get; set; }
public LibObject(string name)
{
this.Name = name;
}
}
My main problem is in the XAML, and styling this TreeView. I need to have a specific style for a "root" item, and a specific style for a "leaf". Thing is, that one item in the bound list is "Root->Leaf", and another is "Root->Child->Leaf".
I tried this:
<TreeView x:Name="myTree" ItemsSource="{x:Static local:myDataList}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=List}" >
<Grid>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<CheckBox IsChecked="True" Content="HeaderCheckbox"/>
</StackPanel>
</Grid>
<HierarchicalDataTemplate.ItemTemplate >
<DataTemplate>
<Grid>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="True" Content="LeafCheckbox" />
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
</Grid>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
This obviously works fine for the "Root->Leaf" item, but not for the "Root-Child-Leaf".
The XAML implementation seems to be more of a "hard coded" solution, where I know that the item layout is always "Root->Leaf" - how do I make this dynamic?
Again, I have seen solutions to different levels (including using converters), but the problem i'm having is that I need specific styles to root and leaf and nothing for levels in between.
I'm wondering if I'm looking at this completely wrong ...
Easy way to do this. Pull the DataTemplates out of the TreeView and put them in the resources section. Specify the DataType property for each DataTemplate, but do not include a key. The ItemTemplateSelector (a property of type DataTemplateSelector) on the TreeView will do the magic of using whichever DataTemplate suits the correct item type.
Create a HierarchicalDataTemplate for types Root and Child, and a DataTemplate for type Leaf.
Something like this:
<Window.Resources>
<ResourceDictionary>
<DataTemplate DataType="{x:Type local:Leaf}">
<Grid>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="True" Content="LeafCheckbox" />
<TextBlock Text="{Binding Path=SomeValue}"/>
</StackPanel>
</Grid>
</DataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Child}"
ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Child " />
<TextBlock Text="{Binding Path=SomeValue}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Root}"
ItemsSource="{Binding Children}">
<Grid>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Root " />
<TextBlock Text="{Binding Path=SomeValue}" />
</StackPanel>
</Grid>
</HierarchicalDataTemplate>
</ResourceDictionary>
</Window.Resources>
<Grid>
<TreeView x:Name="myTree" ItemsSource="{Binding}" />
</Grid>

Resources