using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
namespace WpfApplication1 {
public partial class Window1 : Window {
private ObservableCollection<Item> _items = new ObservableCollection<Item>();
public ObservableCollection<Item> Items {
get { return _items; }
}
public static readonly RoutedCommand AddChildItem = new RoutedCommand("AddChildItem", typeof(Window1));
public Window1() {
InitializeComponent();
_items.Add(new Item { ItemName = "One" });
_items.Add(new Item { ItemName = "Two" });
_items.Add(new Item { ItemName = "Three" });
this.DataContext = this;
}
private void AddChildItem_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
if(tv1 != null && tv1.SelectedItem != null) {
e.CanExecute = true;
}
}
private void AddChildItem_Executed(object sender, ExecutedRoutedEventArgs e) {
if(tv1.SelectedItem != null) {
(tv1.SelectedItem as Item).AddChildItem();
}
}
// Without this event handler you will see the problem
private void TreeViewItem_Selected(object sender, RoutedEventArgs e){
TreeViewItem tvi = e.OriginalSource as TreeViewItem;
if(tvi != null && !tvi.IsFocused) {
tvi.Focus();
}
}
}
public class Item : INotifyPropertyChanged {
private string _itemName = "New Item";
public string ItemName {
get { return _itemName; }
set { _itemName = value; }
}
private ObservableCollection<Item> _children = new ObservableCollection<Item>();
public ObservableCollection<Item> Children {
get { return _children; }
}
private Item _parent = null;
public Item Parent {
get { return _parent; }
}
public Item() : this(null) { }
public Item(Item parent) {
_parent = parent;
}
public void AddChildItem() {
Item i = new Item(this);
_children.Add(i);
i.IsSelected = true;
}
private bool _isSelected;
public bool IsSelected {
get { return _isSelected; }
set {
if(_isSelected != value) {
_isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
private bool _isExpanded = true;
public bool IsExpanded {
get { return _isExpanded; }
set {
if(_isExpanded != value) {
_isExpanded = value;
if(_isExpanded && _parent != null) {
_parent.IsExpanded = true;
}
OnPropertyChanged("IsExpanded");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
protected virtual void OnPropertyChanged(string propertyName) {
if(this.PropertyChanged != null) {
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}