in WPF ,I have a treeview that is bind to a hierarchical list. when I want to insert a new node to the tree and edit the name of that new node (like folder treeview in Windows), I can not select new node programmatically. I can select parent node or even I can select the new node after insertion. but I want to select new node while I am inserting new node.
<HierarchicalDataTemplate x:Key="hierarchi" ItemsSource="{Binding Path=Items}" >
<StackPanel Orientation="Horizontal" Margin="2" MouseLeftButtonDown="Item_MouseLeftButtonDown" Tag="{Binding}" >
<Image Name="itemImage" Source="{Binding Path=Image}" Height="16" Width="16"/>
<TextBlock Name="textBlockName" VerticalAlignment="Center" Text="{Binding Path=Name}" FontFamily="Tahoma" FontSize="12" />
<TextBox Name="textBoxName" VerticalAlignment="Center" Text="{Binding Path=Name,Mode=TwoWay}" Visibility="Hidden" FontFamily="Tahoma" FontSize="12" KeyDown="textBoxName_KeyDown" LostFocus="textBoxName_LostFocus"/>
</StackPanel>
</HierarchicalDataTemplate>
my data model is something like this:
public class Model:INotifyPropertyChanged { //other methods and properties are removed. private string name; public string Name { get { return name; } set { name = value; OnPropertyChange("Name"); } } private ObservableCollection items = null; public ObservableCollection Items { get { return items; } set { items = value; OnPropertyChange("Items"); } } }
here is the code of adding a node :
private void buttonNew_Click(object sender, RoutedEventArgs e)
{
if (treeView.SelectedItem is Model)
{
Model parent= (Model)treeView.SelectedItem;
Model newItem = new Model();
newItem.Parent = post;
newItem.Name = "New";
newItem.ParentID = parent.ID;
parent.Items.Add(newItem);
TreeViewItem item = GetTreeViewItem(newItem);
//problem is here, item is null.
if(item!=null)
item.IsSelected = true;
}
}
private TreeViewItem GetTreeViewItem(Model node)
{
// a recursive method for going to root of the tree and coming back
if (node.Parent == null)
{
DependencyObject dObject = treeView.ItemContainerGenerator.ContainerFromItem(node);
return (TreeViewItem)dObject;
}
TreeViewItem parentItem = GetTreeViewItem(node.Parent);
if (parentItem == null)
return null;
DependencyObject Dependency = parentItem.ItemContainerGenerator.ContainerFromItem(node);
return (TreeViewItem)Dependency;
}
I am sure I have to update or render treeview datasource, but I don't know how.