在C#中按数字排序TreeViewItems列表

Eri*_*ark 1 c# sorting wpf list treeviewitem

这个问题是对这个问题的跟进.我目前的总体目标是根据输入的值以数字升序添加到我的程序TreeViewItem(我的TreeViewItem运行时添加了子节点)header.

我收到使用一个答案ModelView,一个工具,我不是那么熟悉了,我也被告知,这可以通过使用来完成ListTreeViewItems.List由于我缺乏经验,我决定探索这个选项ModelView.

在我的研究,我了解到ListsTreeViewItems有一点不同,因为你真的不喜欢你可以在引用它们array.这使得他们更难以完成工作.我将解释我当前的方法并发布我的代码.请引导我朝着正确的方向前进,并提供编码解决方案的答案.我目前仍然坚持我的treeViewListAdd功能.我在评论中编写了伪代码,用于解释我要对该区域进行的操作.

*注意:我是TreeViewItem从一个单独的窗口添加到我的

现在我的添加TreeViewItem过程包括:

  1. 检查输入的项目是否为数字(DONE)
  2. if不是数字,break操作(DONE)
  3. else- 继续添加子项(DONE)
  4. 检查重复的孩子(DONE)
  5. if找到重复break操作(DONE)
  6. else- 继续(完成)
  7. 创建ListTreeViewItem (DONE -但没有实现)
  8. TreeViewItem为新子节点创建(DONE)
  9. TVI header是根据用户文字设置的textBox (DONE)
  10. 传递给尝试添加到List数字顺序的函数(问题区域)
  11. 添加排序ListTreeViewItem主窗口(问题区域)

我目前的代码:

//OKAY - Add child to TreeViewItem in Main Window
private void button2_Click(object sender, RoutedEventArgs e)
{
    //STEP 1: Checks to see if entered text is a numerical value
    string Str = textBox1.Text.Trim();
    double Num;
    bool isNum = double.TryParse(Str, out Num);

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

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

        //STEP 4: Check for duplicate
        //declare TreeViewItem from mainWindow
        TreeViewItem locations = mainWindow.TreeViewItem;
        //Passes to function -- checks for DUPLICATE locations
        CheckForDuplicate(locations.Items, textBox1.Text);

        //STEP 5: 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 //STEP 6: else -- create child node
        {
            //STEP 7
            List<TreeViewItem> treeViewList = new List<TreeViewItem>();

            //STEP 8: Creates child TreeViewItem for TVI in main window
            TreeViewItem newLocation = new TreeViewItem();

            //STEP 9: Sets Headers for new child nodes
            newLocation.Header = textBox1.Text;

            //STEP 10: Pass to function -- adds/sorts List in numerical ascending order
            treeViewListAdd(ref treeViewList, newLocation);

            //STEP 11: Add children to TVI in main window
            //This step will of course need to be changed to add the list
            //instead of just the child node
            mainWindow.TreeViewItem.Items.Add(newLocation);
        }
    }
}

//STEP 4: 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;
        }
}

//STEP 10: Adds to the TreeViewItem list in numerical ascending order
private void treeViewListAdd(ref List<TreeViewItem> currentList, TreeViewItem addLocation)
{
        //if there are no TreeViewItems in the list, add the current one
        if (currentList.Count() == 0)
            currentList.Add(addLocation);
        else
        {
            //gets the index of the last item in the List
            int lastItem = currentList.Count() - 1;

            /*
            if (value in header > lastItem)
                currentList.Add(addLocation);
            else
            {
                //iterate through list and add TreeViewItem
                //where appropriate
            }
            **/
        }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助.我试图表明我一直在研究这个问题并尝试自己能做的一切.

根据要求,这是我的结构TreeView.从第3级到第3级的所有内容都由用户动态添加...

在此输入图像描述

Fed*_*gui 5

好.删除所有代码并从头开始.

1:在WPF中编写一行代码之前,必须先阅读MVVM.

你可以在这里,这里这里阅读它

<Window x:Class="MiscSamples.SortedTreeView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:cmp="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        Title="SortedTreeView" Height="300" Width="300">
    <DockPanel>
        <TextBox Text="{Binding NewValueString}" DockPanel.Dock="Top"/>
        <Button Click="AddNewItem" DockPanel.Dock="Top" Content="Add"/>
        <TreeView ItemsSource="{Binding ItemsView}" SelectedItemChanged="OnSelectedItemChanged">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding ItemsView}">
                    <TextBlock Text="{Binding Value}"/>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </DockPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

代码背后:

public partial class SortedTreeView : Window
{
    public SortedTreeViewWindowViewModel ViewModel { get { return DataContext as SortedTreeViewWindowViewModel; } set { DataContext = value; } }

    public SortedTreeView()
    {
        InitializeComponent();
        ViewModel = new SortedTreeViewWindowViewModel()
            {
                Items = {new TreeViewModel(1)}
            };
    }

    private void AddNewItem(object sender, RoutedEventArgs e)
    {
        ViewModel.AddNewItem();
    }

    //Added due to limitation of TreeViewItem described in http://stackoverflow.com/questions/1000040/selecteditem-in-a-wpf-treeview
    private void OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        ViewModel.SelectedItem = e.NewValue as TreeViewModel;
    }
}
Run Code Online (Sandbox Code Playgroud)

2:您可以注意到的第一件事是"守则背后"没有任何意义.它只是将功能委托给ViewModel(而不是ModelView,这是一个拼写错误)

这是为什么?

因为这是一个更好的方法.期.将应用程序逻辑/业务逻辑和数据分离 UI 分离是任何开发人员都应该遇到的最好的事情.

那么,ViewModel是关于什么的?

3: ViewModel公开Properties包含要在View中显示的Data,并Methods包含与Data一起操作的逻辑.

所以它很简单:

public class SortedTreeViewWindowViewModel: PropertyChangedBase
{
    private string _newValueString;
    public int? NewValue { get; set; }

    public string NewValueString
    {
        get { return _newValueString; }
        set
        {
            _newValueString = value;
            int integervalue;

            //If the text is a valid numeric value, use that to create a new node.
            if (int.TryParse(value, out integervalue))
                NewValue = integervalue;
            else
                NewValue = null;

            OnPropertyChanged("NewValueString");
        }
    }

    public TreeViewModel SelectedItem { get; set; }

    public ObservableCollection<TreeViewModel> Items { get; set; }

    public ICollectionView ItemsView { get; set; }

    public SortedTreeViewWindowViewModel()
    {
        Items = new ObservableCollection<TreeViewModel>();
        ItemsView = new ListCollectionView(Items) {SortDescriptions = { new SortDescription("Value",ListSortDirection.Ascending)}};
    }

    public void AddNewItem()
    {
        ObservableCollection<TreeViewModel> targetcollection;

        //Insert the New Node as a Root node if nothing is selected.
        targetcollection = SelectedItem == null ? Items : SelectedItem.Items;

        if (NewValue != null && !targetcollection.Any(x => x.Value == NewValue))
        {
            targetcollection.Add(new TreeViewModel(NewValue.Value));
            NewValueString = string.Empty;    
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

看到?通过该AddNewItem()方法中的5行代码满足您的所有11个要求.没有Header.ToString()东西,没有任何东西,没有可怕的代码背后的方法.

简单,简单的属性和INotifyPropertyChanged.

排序怎么样?

4:排序由CollectionView,执行,它发生在ViewModel级别,而不是View Level.

为什么?

因为数据与UI中的可视化表示是分开的.

5:最后,这是实际的数据项:

public class TreeViewModel: PropertyChangedBase
{
    public int Value { get; set; }

    public ObservableCollection<TreeViewModel> Items { get; set; }

    public CollectionView ItemsView { get; set; }

    public TreeViewModel(int value)
    {
        Items = new ObservableCollection<TreeViewModel>();
        ItemsView = new ListCollectionView(Items)
            {
                SortDescriptions =
                    {
                        new SortDescription("Value",ListSortDirection.Ascending)
                    }
            };
        Value = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个保存数据的类,在本例中是一个intValue,因为你只关心数字,所以这是正确的数据类型,然后是一个ObservableCollection将保存子节点的数据,再次CollectionView负责排序.

6:每当你在WPF中使用DataBinding时(这对于所有这些MVVM都是必不可少的)你需要实现INotifyPropertyChanged,所以这是PropertyChangedBase所有ViewModes继承自的类:

public class PropertyChangedBase:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        Application.Current.Dispatcher.BeginInvoke((Action) (() =>
                                                                 {
                                                                     PropertyChangedEventHandler handler = PropertyChanged;
                                                                     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
                                                                 }));
    }
}
Run Code Online (Sandbox Code Playgroud)

无论在哪里有财产变化,您都需要通过以下方式通知:

OnPropertyChanged("PropertyName");
Run Code Online (Sandbox Code Playgroud)

如在

OnPropertyChanged("NewValueString");
Run Code Online (Sandbox Code Playgroud)

这就是结果:

在此输入图像描述

  • 只需复制并粘贴我的所有代码,File -> New Project -> WPF Application然后自己查看结果.

  • 如果您需要我澄清任何事情,请告诉我.