如何从ItemsSource获取双击TreeViewItem的子TextBlock的项目?

时间:2015-09-02 08:24:18

标签: c# wpf

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,而是来自代码。

2 个答案:

答案 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