Here is a little example for your special case using ModelView
, Binding
and CollectionView
ModelViews
public class MainViewModel
{
private readonly ObservableCollection<TreeItemViewModel> internalChildrens;
public MainViewModel(string topLevelHeader) {
this.TopLevelHeader = topLevelHeader;
this.internalChildrens = new ObservableCollection<TreeItemViewModel>();
var collView = CollectionViewSource.GetDefaultView(this.internalChildrens);
collView.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));
this.Childrens = collView;
}
public string TopLevelHeader { get; set; }
public IEnumerable Childrens { get; set; }
public bool AddNewChildren(double num) {
var numExists = this.internalChildrens.FirstOrDefault(c => c.Header == num) != null;
if (!numExists) {
this.internalChildrens.Add(new TreeItemViewModel() {Header = num});
}
return numExists;
}
}
public class TreeItemViewModel
{
public double Header { get; set; }
}
Xaml
<Window x:Class="WpfStackOverflowSpielWiese.Window21"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window21"
Height="300"
Width="300"
x:Name="tvExample">
<Grid DataContext="{Binding ElementName=tvExample, Path=ViewModel, Mode=OneWay}">
<StackPanel Orientation="Vertical">
<TextBox x:Name="tb" />
<Button Content="Add"
Click="AddNewItemOnClick" />
<TreeView>
<TreeViewItem Header="{Binding TopLevelHeader, Mode=OneWay}"
ItemsSource="{Binding Childrens, Mode=OneWay}">
<TreeViewItem.ItemTemplate>
<HierarchicalDataTemplate>
<TextBlock Text="{Binding Header}" />
</HierarchicalDataTemplate>
</TreeViewItem.ItemTemplate>
</TreeViewItem>
</TreeView>
</StackPanel>
</Grid>
</Window>
Xaml code behind
public partial class Window21 : Window
{
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register("ViewModel", typeof(MainViewModel), typeof(Window21), new PropertyMetadata(default(MainViewModel)));
public MainViewModel ViewModel {
get { return (MainViewModel)this.GetValue(ViewModelProperty); }
set { this.SetValue(ViewModelProperty, value); }
}
public Window21() {
this.InitializeComponent();
this.ViewModel = new MainViewModel("TopLevel");
}
private void AddNewItemOnClick(object sender, RoutedEventArgs e) {
double Num;
var isNum = double.TryParse(this.tb.Text, out Num);
//If not numerical value, warn user
if (isNum == false) {
MessageBox.Show("Value must be Numerical");
return;
}
var isDuplicate = this.ViewModel.AddNewChildren(Num);
if (isDuplicate) {
MessageBox.Show("Sorry, the number you entered is a duplicate of a current node, please try again.");
return;
}
}
}
hope that helps