我TreeView
TreeViewItems
ItemsSource
ObservableCollection<MyClass>
<{1}}
var myList = new ObservableCollection<MyClass>();
TreeView treeView = new TreeView();
TreeViewItem treeViewItem = new TreeViewItem {
Header = headerStackPanel,
ItemsSource = myList
};
treeView.Items.Add(treeViewItem);
双击相应的MyClass
时如何获取TextBlock
的对象?我唯一能做的就是MyClass.ToString()
,它存储在TextBlock.Text
中:
treeViewItem.MouseDoubleClick += (sender, args) => {
TextBlock tb = args.OriginalSource as TextBlock;
if (tb == null) {
return;
}
string myClassToString = tb.Text;
};
另外:不是来自XAML,而是来自代码。
答案 0 :(得分:0)
您可以获取TextBlock的DataContext。
答案 1 :(得分:0)
将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;
}
};
或以同样的方式使用DataContext
的{{1}}属性:
TextBlock