以数字顺序将子节点添加到TreeViewItem

时间:2013-07-29 18:40:20

标签: c# wpf treeviewitem

我有一个带有TreeView项目的程序,该项目包含具有数字headers的子节点。当adding子节点到TreeViewItem时我想用数字添加它们,但我不知道如何在其他节点之间添加节点。

我猜我会调用一个函数来排序子节点,将标题转换为integers,将标题与输入的值进行比较,然后在节点标题大于输入的值。必须在节点之前输入新节点,其标头大于添加的新节点。

这是最好的方法,还是有更好的方法?请展示最简单的方法。仅供参考,我的TreeViewItem位于我的主窗口,正在从一个单独的窗口进行处理。

这可以让您了解我如何将子节点添加到TreeViewItem

//Global boolean    
// bool isDuplicate;

//OKAY - Add TreeViewItems to location & Checks if location value is numerical
private void button2_Click(object sender, RoutedEventArgs e)
{
      //Checks to see if TreeViewItem is a numerical value
      string Str = textBox1.Text.Trim();
      double Num;

      bool isNum = double.TryParse(Str, out Num);

      //If not numerical value, warn user
      if (isNum == false)
          MessageBox.Show("Value must be Numerical");
      else //else, add location
      {
          //close window
          this.Close();

          //Query for Window1
          var mainWindow = Application.Current.Windows
              .Cast<Window1>()
              .FirstOrDefault(window => window is Window1) as Window1;

          //declare TreeViewItem from mainWindow
          TreeViewItem locations = mainWindow.TreeViewItem;

          //Passes to function -- checks for DUPLICATE locations
          CheckForDuplicate(TreeViewItem.Items, textBox1.Text);

          //if Duplicate exists -- warn user
          if (isDuplicate == true)
             MessageBox.Show("Sorry, the number you entered is a duplicate of a current node, please try again.");
          else //else -- create node
          {
               //Creates TreeViewItems for Location
               TreeViewItem newNode = new TreeViewItem();

               //Sets Headers for new locations
               newNode.Header = textBox1.Text;

               //Add TreeView Item to Locations & Blocking Database
               mainWindow.TreeViewItem.Items.Add(newNode);

           }
       }
}

//Checks to see whether the header entered is a DUPLICATE
private void CheckForDuplicate(ItemCollection treeViewItems, string input)
{
      for (int index = 0; index < treeViewItems.Count; index++)
      {
             TreeViewItem item = (TreeViewItem)treeViewItems[index];
             string header = item.Header.ToString();

             if (header == input)
             {
                   isDuplicate = true;
                   break;
             }
             else
                   isDuplicate = false;
      }
}

谢谢。

1 个答案:

答案 0 :(得分:1)

以下是使用ModelViewBindingCollectionView

的特殊情况的示例

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代码

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;
    }
  }
}

希望有所帮助