2011-08-23 97 views
0

的財產我有這樣的綁定TreeView控件:綁定樹型視圖到對象

<TreeView ItemsSource="{Binding}"> 
<TreeView.Resources> 
    <HierarchicalDataTemplate DataType="{x:Type Trees:ItemTreeNode}" 
          ItemsSource="{Binding Path=Children}"> 
    <StackPanel Orientation="Horizontal" Tag=""> 
     <Image VerticalAlignment="Center" Margin="0,0,4,0" Source="{Binding Path=Icon}" /> 
     <TextBlock VerticalAlignment="Center" Text="{Binding Path=Text}" /> 
    </StackPanel> 
    </HierarchicalDataTemplate> 
</TreeView.Resources> 
</TreeView> 

而且我隔壁班:

public class ItemTreeNode : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    public ObservableCollection<ItemTreeNode> Children { get; set; } 

    public ImageSource Icon {get; set;} 
    public string Text {get; set;} 
    public TreeViewItem VisualItem { get; set; } 
} 

是否可以綁定一個TreeViewItem參考VisualItem,所以我可以通過VisualItem尋址來獲取TreeViewItem?

+0

設計方面你的模型不應該在UI的任何引用的。 –

回答

0

你可以嘗試,但你會收到一個綁定錯誤,因爲TreeView項目的ItemsSourceCollection類型不是TreeViewItem類型。

因此,設置一個ItemTreeNode公共屬性來將SelectedItem綁定到。然後,在你的樹的SelectedItemChanged情況下,通過使用ItemContainerGenerator.ContainerFromItem方法,這種搶樹型視圖:

var tvi = myTreeView.ItemContainerGenerator.ContainerFromItem(selectedItem) as TreeViewItem;