将属性绑定到 TreeView 的 SelectedItem 可以解决您的问题。下面的代码表达了我正在考虑的内容。对于您拥有的两个 UC,您可以为 SelectedItem 公开一个属性。
XAML:
<TreeView x:Name="Tree1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<TextBlock Text="{Binding ElementName=Tree1,Path=SelectedItem.Name}" />
物品实体
public class Item
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
private Collection<Item> items;
public Collection<Item> Items { get { return items; } }
public Item()
{
items = new Collection<Item>();
}
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
绑定源
Item item = new Item { Name = "A" };
item.Items.Add(new Item { Name = "A_1" });
item.Items.Add(new Item { Name = "A_2" });
item.Items.Add(new Item { Name = "A_3" });
Tree1.ItemsSource = new Collection<Item>() { item };