I'm learning WPF, and I think I'm missing something with user controls. I'll try and demonstrate by example. Basically, suppose I have a treeview, and I want to bind a labels text to the treeviews selectedItem. This seems simple :
<!-- Window.xaml -->
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<TreeView Name="MyTreeView">
<TreeViewItem Header="Root">
<TreeViewItem Header="Item1"></TreeViewItem>
<TreeViewItem Header="Item2"></TreeViewItem>
</TreeViewItem>
</TreeView>
<Label Content="{Binding ElementName=MyTreeView, Path=SelectedItem.Header}" Grid.Row="1"></Label>
</Grid>
Now, to complicate things I'll add a user control into the mix. The user control is basically a TreeView in a grid :
<!-- ExampleUserControl.xaml -->
<UserControl>
<Grid>
<TreeView Name="UserControlTreeView">
<TreeViewItem Header="Root">
<TreeViewItem Header="Item1"></TreeViewItem>
<TreeViewItem Header="Item2"></TreeViewItem>
</TreeViewItem>
</TreeView>
</Grid>
</UserControl>
The intent is to replace the vanilla treeview used above with the usercontrol, and have the labels content changed based on what is selected. So, I try something like this :
<Window>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<local:ExampleUserControl1 x:Name="MyUserControl">
</local:ExampleUserControl1>
<Label Content="{Binding ElementName=MyUserControl, Path=SelectedItem.Header}" Grid.Row="1"></Label>
</Grid>
</Window>
This compiles and runs, but when I select items in the treeview, the label doesn't change. I think I understand why : the user control contains a treeview, but is clearly not a treeview. I'm not sure on the best way to fix this. I can think of one way that seems problematic :
- Add a property 'SelectedItem' to the user control in code, that returns the treeviews selected item.
This would work for one property, or a few, but the thought of doing this for each property in treeview seems like a serious waste of code + time. Is there some way to still use the user control, but make it behave like a normal TreeView?