如何为HierarchicalDataTemplate模板生成的控件添加事件?
一般的模板直接就能在模板中的控件属性中设置,可是HierarchicalDataTemplate直接生成了TreeViewItem(ListBoxItem也是一样),没地方设置啊
<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:WpfApplication3" Title="MainWindow" Height="350" Width="525"> <Grid> <TreeView x:Name="Tree" ItemsSource="{Binding}"> <TreeView.Resources> <DataTemplate x:Key="aTemplate" DataType="{x:Type src:AB}"> <TextBox Text="{Binding Path=abc}" /> </DataTemplate> </TreeView.Resources> <TreeView.ItemTemplate> <HierarchicalDataTemplate DataType="{x:Type src:A}" ItemsSource="{Binding Path=ab}" ItemTemplate="{StaticResource aTemplate}"> <TextBox x:Name="NameBox" Width="160" Text="{Binding Path=name}" LostFocus="textBox_LostFocus" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> </Grid></Window>
using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace WpfApplication3{ /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); ObservableCollection<A> a = new ObservableCollection<A>(); a.Add(new A()); a[0].name = "thy"; ObservableCollection<AB> ab = new ObservableCollection<AB>(); ab.Add(new AB()); ab[0].abc = "38"; a[0].ab = ab; Tree.DataContext = a; } } class A { public string name { get; set; } public ObservableCollection<AB> ab { get; set; } } class AB { public string abc { get; set; } }}