如何从ItemsSource获得项目双击TreeViewItem's子TextBlock

本文关键字:TextBlock TreeViewItem 双击 ItemsSource 项目 | 更新日期: 2023-09-27 18:10:59

我有一个TreeViewTreeViewItems,其中ItemsSourceObservableCollection<MyClass>

var myList = new ObservableCollection<MyClass>(); 
TreeView treeView = new TreeView();
TreeViewItem treeViewItem = new TreeViewItem {
    Header = headerStackPanel,
    ItemsSource = myList 
};
treeView.Items.Add(treeViewItem);

当双击相应的TextBlock时,我如何获得MyClass的对象?我所做的唯一的事情是获得MyClass.ToString(),它存储在TextBlock.Text:

treeViewItem.MouseDoubleClick += (sender, args) => {
    TextBlock tb = args.OriginalSource as TextBlock;
    if (tb == null) {
         return; 
    }
    string myClassToString = tb.Text;
};

如何从ItemsSource获得项目双击TreeViewItem's子TextBlock

将TreeView的SelectedItem强制转换为MyClass:

treeViewItem.MouseDoubleClick += (sender, args) => {
    if (yourTreeView.SelectedItem is MyClass) {
        var myClass = yourTreeView.SelectedItem as MyClass;
        //Do something with myClass.
    }
    //Additionally in this aproach you can
    //check if selected item is TreeViewItem and get e.g. Header property.
    else if (yourTreeView.SelectedItem is TreeViewItem) {
        var treeViewItem = yourTreeView.SelectedItem as TreeViewItem;
        string header = treeViewItem.Header;
    }       
};

或以同样的方式使用TextBlockDataContext属性:

treeViewItem.MouseDoubleClick += (sender, args) => {
   TextBlock tb = args.OriginalSource as TextBlock;
   if (tb == null) {
       return; 
   }
   else if (tb.DataContext is MyClass) {
       var myClass = tb.DataContext as MyClass;
       //Do something with myClass   
   }      
};

你可以得到你的TextBlock的DataContext .