c# - 在 C# 中对 TreeViewItems 列表进行数字排序

标签 c# wpf list sorting treeviewitem

此问题是 this 的后续问题问题。我现在的总体目标是根据输入的值按数字升序添加到我的程序的 TreeViewItem (我的 TreeViewItem 有子节点在运行时添加到它)在 header 中。

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

在我的研究中,我了解到 TreeViewItemsLists 有点不同,因为您不能像引用 array< 那样引用它们。这使他们更难一起工作。我将解释我当前的方法并发布我的代码。请引导我朝着正确的方向前进,并提供编码解决方案的答案。我目前卡在我的 treeViewListAdd 函数上。我在评论中写了伪代码,说明我想对该区域做什么。

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

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

  1. 检查输入的项目是否为数字(完成)
  2. 如果不是数字,break操作(DONE)
  3. else -- 继续添加子项(完成)
  4. 检查重复的 child (完成)
  5. if 发现重复break 操作(DONE)
  6. else -- 继续(完成)
  7. 创建 TreeViewItemList (完成 -- 但未实现)
  8. 为新的子节点创建TreeViewItem(完成)
  9. TVI headertextBox 中的用户文本设置 (DONE)
  10. 传递给尝试按数字顺序添加到 List 的函数 (问题区域)
  11. 在主窗口 (问题区域)
  12. 中将排序的 List 添加到 TreeViewItem

我当前的代码:

//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
            }
            **/
        }
}

非常感谢您的帮助。我试图表明我一直在努力解决这个问题,并尽我所能。

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

enter image description here

最佳答案

好的。删除所有代码并重新开始。

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

你可以阅读它hereherehere

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

代码隐藏:

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

2:您在上面注意到的第一件事是代码隐藏什么都不做。它只是将功能委托(delegate)给称为 ViewModel 的东西(不是 ModelView,这是一个拼写错误)

Why is that?

因为这是一种更好的方法。时期。将应用程序逻辑/业务逻辑和数据从 UI 中分离解耦对任何开发人员来说都是最好的事情。

So, What's the ViewModel about?

3: ViewModel 公开属性,其中包含要在 View 中显示的数据,以及方法包含操作数据的逻辑。

所以很简单:

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

    }
}

看到了吗? AddNewItem() 方法中的 5 行代码满足了所有 11 项要求。没有 Header.ToString() 东西,没有转换任何东西,没有可怕的代码隐藏方法。

只是简单、简单的属性和 INotifyPropertyChanged

And what about the sorting?

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

Why?

因为数据与其在 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;
    }
}

这是将保存数据的类,在本例中为 int 值,因为您只关心数字,所以这是正确的数据类型,然后是 ObservableCollection 将保存子节点,CollectionView 负责排序。

6: 每当您在 WPF 中使用 DataBinding(这对所有 MVVM 事物都是必不可少的)时,您需要实现 INotifyPropertyChanged,因此这就是 PropertyChangedBase 类所有 ViewModels 继承自:

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

只要属性发生变化,您就需要通过以下方式通知:

OnPropertyChanged("PropertyName");

如在

OnPropertyChanged("NewValueString");

这是结果:

enter image description here

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

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

关于c# - 在 C# 中对 TreeViewItems 列表进行数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17949777/

相关文章:

c# - WPF TextBox Extension无法使用MahApps TextBoxHelper

java - 连接两个列表并更改特定数据

c# - 从字符串/Json url 获取数据

C# ascii游戏碰撞

.net - 适应屏幕和字体设置的 WPF 应用程序(或者,我如何将 DLU 与 WPF 中的单元相关联?)

Python:比较列表中的元素并打印具有最大匹配计数的元素

递归调用中列表到列表的列表

c# - 将单例与依赖注入(inject)一起使用(CaSTLe Windsor)

C# OleDb INSERT INTO 溢出异常

c# - 从类编辑 MainWindow 上的 ListBox