我有这样的问题。我有一个treeview,treeviewitems是在应用程序运行时由我的代码创建的。当我单击treeviewitem时,我想创建一个事件。我该怎么办? 这是我的代码
TreeViewItem tvitem = new TreeViewItem();
tvitem.Header = namhoc;
tvSoDoNamHoc.Items.Add(tvitem);
List<Khoi> dskhoi = TruyCapDuLieu.Instance.getTableKhoi().ToList();
foreach (Khoi k in dskhoi)
{
TreeViewItem tvitems = new TreeViewItem();
tvitems.Header = k.TenK;
tvitem.Items.Add(tvitems);
List<Lop> dslop = TruyCapDuLieu.Instance.getLopForAutoInsertLop(Member.Instance.SetNamHoc, k).ToList();
if (dslop.Count != 0)
{
foreach (Lop l in dslop)
{
TreeViewItem tvitems2 = new TreeViewItem();
tvitems2.Header = l.TenL;
tvitems.Items.Add(tvitems2);
}
}
}
答案 0 :(得分:1)
您想要的事件是SelectedItemChanged
对于处理此问题的替代方法,以下代码在TreeView上创建双向可绑定的SelctedItem属性。您可以使用它来检测何时选择了一项(并在代码中将所选项设置在树上)。
public class perTreeViewHelper : Behavior<TreeView>
{
public object BoundSelectedItem
{
get => GetValue(BoundSelectedItemProperty);
set => SetValue(BoundSelectedItemProperty, value);
}
public static readonly DependencyProperty BoundSelectedItemProperty =
DependencyProperty.Register("BoundSelectedItem",
typeof(object),
typeof(perTreeViewHelper),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
OnBoundSelectedItemChanged));
private static void OnBoundSelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (args.NewValue is perTreeViewItemViewModelBase item)
item.IsSelected = true;
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
}
protected override void OnDetaching()
{
AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
base.OnDetaching();
}
private void OnTreeViewSelectedItemChanged(object obj, RoutedPropertyChangedEventArgs<object> args)
{
BoundSelectedItem = args.NewValue;
}
}
有关我最近的blog post的更多详细信息。