| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483 | using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Windows;using System.Windows.Controls;using System.Windows.Input;using MECF.Framework.UI.Client.ClientBase.Tree;using MECF.Framework.UI.Client.ClientViews.Dialogs;using Microsoft.VisualBasic.FileIO;namespace MECF.Framework.UI.Client.ClientBase.UserControls{    /// <summary>    /// Interaction logic for ParameterNodeTreeViewControl.xaml    /// </summary>    public partial class ParameterNodeTreeViewControl    {        #region Variables        private bool _clearGroupSelectionOnly = false;        #endregion        /// <summary>        /// 父级文件夹。        /// </summary>        private const string PRESET_GROUP_SUB_FOLDER_NAME = "PresetGroups";        public ParameterNodeTreeViewControl()        {            //InitializeComponent();        }        protected override void OnInitialized(System.EventArgs e)        {            InitializeComponent();            base.OnInitialized(e);            LoadPresetGroupFilesList();        }        #region Properties        public static readonly DependencyProperty TreeRootProperty = DependencyProperty.Register(            nameof(TreeRoot), typeof(TreeNode), typeof(ParameterNodeTreeViewControl),            new PropertyMetadata(default(TreeNode), (o, p) =>            {                if (o is ParameterNodeTreeViewControl control)                {                    if (p.NewValue is TreeNode tree)                    {                        tree.TerminalNodeSelectionChanged += (sender, b) =>                        {                            control.RaiseEvent(new RoutedEventArgs(TerminalNodeSelectionChangedEvent, sender));                        };                    }                }            }));        /// <summary>        /// 设置或返回TreeView数据源。        /// </summary>        public TreeNode TreeRoot        {            get => (TreeNode)GetValue(TreeRootProperty);            set => SetValue(TreeRootProperty, value);        }        public static readonly DependencyProperty PresetGroupsFolderNameProperty = DependencyProperty.Register(            "PresetGroupsFolderName", typeof(string), typeof(ParameterNodeTreeViewControl),            new PropertyMetadata(default(string)));        /// <summary>        /// 设置或返回存放预设组信息的子文件夹名称。        /// </summary>        public string PresetGroupsFolderName        {            get => (string)GetValue(PresetGroupsFolderNameProperty);            set => SetValue(PresetGroupsFolderNameProperty, value);        }        #endregion        #region Routed Events        // Register a custom routed event using the Bubble routing strategy.        public static readonly RoutedEvent TerminalNodeSelectionChangedEvent = EventManager.RegisterRoutedEvent(            name: nameof(TerminalNodeSelectionChanged),            routingStrategy: RoutingStrategy.Bubble,            handlerType: typeof(RoutedEventHandler),            ownerType: typeof(ParameterNodeTreeViewControl));        // Provide CLR accessors for assigning an event handler.        public event RoutedEventHandler TerminalNodeSelectionChanged        {            add => AddHandler(TerminalNodeSelectionChangedEvent, value);            remove => RemoveHandler(TerminalNodeSelectionChangedEvent, value);        }        #endregion        #region Methods        /// <summary>        /// 返回组信息文件名的完整路径。        /// </summary>        /// <param name="groupName">组名称</param>        /// <returns></returns>        private string GetPresetGroupFullFileName(string groupName)        {            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, PRESET_GROUP_SUB_FOLDER_NAME,                PresetGroupsFolderName, groupName + ".json");        }        /// <summary>        /// 返回保存组信息的文件夹名称。        /// </summary>        /// <returns></returns>        private string GetPresetGroupsFolderName()        {            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, PRESET_GROUP_SUB_FOLDER_NAME,                PresetGroupsFolderName);        }        /// <summary>        /// 加载指定文件夹内的所有json文件。        /// </summary>        /// <returns></returns>        /// <exception cref="ArgumentException"></exception>        private void LoadPresetGroupFilesList(string selectedGroupName = "")        {            if (string.IsNullOrEmpty(PresetGroupsFolderName))                throw new ArgumentException("the preset group files folder is not set.",                    paramName: nameof(PresetGroupsFolderName));            var folderName = GetPresetGroupsFolderName();            var previousSelection = selectedGroupName;            // 如果未指定下次待加载的项目,则保存当前的选择            if (string.IsNullOrEmpty(previousSelection))                if (cbxPresetList.SelectedItem != null)                    previousSelection = cbxPresetList.SelectedItem.ToString();            // 如果文件夹不存在,返回空列表            if (!Directory.Exists(folderName))            {                Directory.CreateDirectory(folderName);                cbxPresetList.ItemsSource = new List<string>();            }            else            {                var source =                    Directory.EnumerateFiles(folderName, "*.json")                        .Select(Path.GetFileNameWithoutExtension)                        .ToList();                cbxPresetList.ItemsSource = source;                // 重新选择上次的选择                if (string.IsNullOrEmpty(previousSelection) == false)                {                    if (source.FirstOrDefault(x => x == previousSelection) != null)                        cbxPresetList.SelectedItem = previousSelection;                }                else                {                    // 如果TreeView还没有加载内容,则不要自动选择                    if (TreeRoot != null)                        cbxPresetList.SelectedIndex = 0;                }            }        }        /// <summary>        /// 仅清空Group下拉框的选项,而不清除TreeView的选择状态。        /// <para>通常用于DataGrid中删除条目后,清除Group选项。</para>        /// </summary>        public void ClearPresetGroupSelectionOnly()        {            _clearGroupSelectionOnly = true;            cbxPresetList.SelectedIndex = -1;            _clearGroupSelectionOnly = false;        }                #endregion        #region Events         /// <summary>        /// 重新加载组列表。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void BtnRefreshPresetList_OnClick(object sender, RoutedEventArgs e)        {            try            {                LoadPresetGroupFilesList();            }            catch (Exception ex)            {                var err = $"Unable to refresh the group list, {ex.Message}";                MessageBox.Show(err, "Error", MessageBoxButton.OK,                    MessageBoxImage.Error);            }        }        /// <summary>        /// 新建组。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void BtnNewGroup_OnClick(object sender, RoutedEventArgs e)        {            try            {                TreeRoot.UnselectAll();                cbxPresetList.SelectedIndex = -1;            }            catch (Exception ex)            {                var err = $"Unable to create new group, {ex.Message}";                MessageBox.Show(err, "Error", MessageBoxButton.OK,                    MessageBoxImage.Error);            }        }        /// <summary>        /// 保存组。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void BtnSave_OnClick(object sender, RoutedEventArgs e)        {            var groupName = "";            //if (TreeRoot.SelectedTerminalCount > TreeNode.QUERY_LIMIT_COUNT)            //{            //    MessageBox.Show($"Too many items are selected, it's limited to {TreeNode.QUERY_LIMIT_COUNT}.",            //        "Error", MessageBoxButton.OK,            //        MessageBoxImage.Error);            //    return;            //}            if (cbxPresetList.SelectedIndex == -1)            {                var dlg = new PresetGroupSaveDialog("Save Group", cbxPresetList.ItemsSource?.Cast<string>());                var ret = dlg.ShowDialog();                if (ret.HasValue && ret.Value == true)                {                    groupName = dlg.GroupName;                }                else                {                    return;                }            }            else            {                groupName = cbxPresetList.SelectedItem.ToString();            }            try            {                // 保存                TreeNodeSelectionGroupInfo.SaveToJsonFile(GetPresetGroupFullFileName(groupName), TreeRoot);                LoadPresetGroupFilesList(groupName);            }            catch (Exception ex)            {                var err = $"Unable to save group {groupName}, {ex.Message}";                MessageBox.Show(err, "Error", MessageBoxButton.OK,                    MessageBoxImage.Error);            }        }        /// <summary>        /// 另存为组。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void BtnSaveAs_OnClick(object sender, RoutedEventArgs e)        {            if (cbxPresetList.SelectedIndex == -1)            {                MessageBox.Show("No group is selected.", "Error", MessageBoxButton.OK,                    MessageBoxImage.Error);                return;            }            var newName = $"Copy of {cbxPresetList.SelectedValue}";            var dlg = new PresetGroupSaveDialog("Save As Group",                 cbxPresetList.ItemsSource?.Cast<string>(),                newName);            var ret = dlg.ShowDialog();            if (ret.HasValue && ret.Value)            {                var groupName = cbxPresetList.SelectedItem.ToString();                try                {                    // 保存                    TreeNodeSelectionGroupInfo.SaveToJsonFile(GetPresetGroupFullFileName(groupName), TreeRoot);                    // 保存一个空文件                    TreeNodeSelectionGroupInfo.SaveToJsonFile(GetPresetGroupFullFileName(dlg.GroupName), TreeRoot);                    LoadPresetGroupFilesList(dlg.GroupName);                }                catch (Exception ex)                {                    var err = $"Unable to save as group {groupName}, {ex.Message}";                    MessageBox.Show(err, "Error", MessageBoxButton.OK,                        MessageBoxImage.Error);                }            }        }        /// <summary>        /// 选择组。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void CbxPresetList_OnSelectionChanged(object sender, SelectionChangedEventArgs e)        {            if (cbxPresetList.SelectedIndex == -1)            {                //                 if (_clearGroupSelectionOnly)                    return;                TreeRoot.UnselectAll();                return;            }            var groupName = cbxPresetList.SelectedValue.ToString();            try            {                TreeNodeSelectionGroupInfo.RecoveryFromJsonFile(GetPresetGroupFullFileName(groupName), TreeRoot);            }            catch (Exception ex)            {                var err = $"Unable to recovery group {groupName}, {ex.Message}";                MessageBox.Show(err, "Error", MessageBoxButton.OK,                    MessageBoxImage.Error);            }        }        /// <summary>        /// 删除组。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void BtnDelete_OnClick(object sender, RoutedEventArgs e)        {            // 如果没选中任何组,忽略操作            if (cbxPresetList.SelectedIndex == -1)                return;            var groupName = cbxPresetList.SelectedItem.ToString();            if (string.IsNullOrEmpty(groupName))                return;            var ret = MessageBox.Show($"Are you sure to delete the group {groupName}", "Warning",                MessageBoxButton.YesNo, MessageBoxImage.Question);            if (ret == MessageBoxResult.Yes)            {                try                {                    FileSystem.DeleteFile(GetPresetGroupFullFileName(groupName), UIOption.OnlyErrorDialogs,                        RecycleOption.SendToRecycleBin);                    LoadPresetGroupFilesList();                }                catch (Exception ex)                {                    var err = $"Unable to delete group {groupName}, {ex.Message}";                    MessageBox.Show(err, "Error", MessageBoxButton.OK,                        MessageBoxImage.Error);                }            }        }        /// <summary>        /// 折叠所有节点。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void BtnCollapseAll_OnClick(object sender, RoutedEventArgs e)        {            TreeRoot.CollapseAll();        }        /// <summary>        /// 展开所有节点。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void BtnExpandAll_OnClick(object sender, RoutedEventArgs e)        {            TreeRoot.ExpandAll();        }        /// <summary>        /// 应用筛选器。        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        /// <exception cref="NotImplementedException"></exception>        private void BtnApplyFilter_OnClick(object sender, RoutedEventArgs e)        {            TreeRoot.SuspendUpdate();            TreeRoot.ApplyFilter(txtFilterKeyword.Text);            TreeRoot.ResumeUpdate();            txtFilterKeyword.SelectAll();            txtFilterKeyword.Focus();        }        /// <summary>        /// 清除筛选器        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void BtnClearFilter_OnClick(object sender, RoutedEventArgs e)        {            TreeRoot.SuspendUpdate();            TreeRoot.ClearFilter();            TreeRoot.ResumeUpdate();            txtFilterKeyword.Text = "";            txtFilterKeyword.Focus();        }        private void TxtFilterKeyword_OnKeyDown(object sender, KeyEventArgs e)        {            if (e.Key != Key.Enter)                 return;                        TreeRoot.ApplyFilter(txtFilterKeyword.Text);            txtFilterKeyword.SelectAll();            txtFilterKeyword.Focus();        }        private void BtnShowSelectedOnly_OnClick(object sender, RoutedEventArgs e)        {            TreeRoot.ShowSelectedOnly();        }        private void BtnShowAll_OnClick(object sender, RoutedEventArgs e)        {            TreeRoot.ShowAll();        }        #endregion        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)        {            var sss = e;            var textBlock = sender as TextBlock;            if (textBlock != null)            {                var data = textBlock.DataContext as TreeNode;                if (data != null)                {                    data.IsSelected = !data.IsSelected;                }            }        }    }}
 |