using System.Windows; using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Media.Imaging; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Nice3point.Revit.Toolkit.External.Handlers; using Szmedi.RvKits.FamilyTools; namespace Szmedi.RvKits.FamilyLibrary { /// /// LocalFamily.xaml 的交互逻辑 /// public partial class LocalFamsLibWin { #region 获取文件缩略图 private readonly ActionEventHandler handler = new(); /// /// 加载缩略图资源 /// /// /// private BitmapSource LoadImage(string filename) { var bm = WindowsThumbnailProvider.GetThumbnail(filename, 128, 128, ThumbnailOptions.None); return Imaging.CreateBitmapSourceFromHBitmap( bm.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions() ); } #endregion #region 获取页面数据源 /// /// 获取页面数据源 /// /// /// private List GetListviewItems(JumpOperation jo) { List familyFileList = []; var list = pageFamilyFileList.GetPageData(jo); foreach (var file in list) { familyFileList.Add( new RvComponent { Title = Path.GetFileNameWithoutExtension(file.ToString()), ImageData = LoadImage(file.ToString()), Path = file.FullName } ); } return familyFileList; } #endregion //private string GetConfigPath() //{ // //ExeConfigurationFileMap map = new ExeConfigurationFileMap(); // //map.ExeConfigFilename = "\\FamilyTools.dll.config"; // //Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); // //string path = config.AppSettings.Settings["FamilyPath"].Value;//若路径存在则自动获取该路径 // //return path; // Assembly assembly = Assembly.GetCallingAssembly(); // Uri uri = new Uri(Path.GetDirectoryName(assembly.CodeBase)); // ExeConfigurationFileMap map = new ExeConfigurationFileMap(); // map.ExeConfigFilename = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".dll.config"); // Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); // string _Loadpath = config.AppSettings.Settings["FamilyPath"].Value; //若路径存在则自动获取该路径 // return _Loadpath; //} #region 绑定ListView首页数据源 /// /// 绑定ListView首页数据源 /// private void BindListViewSource() { //Stopwatch stw = new Stopwatch(); //stw.Start(); //stw.Stop(); //TimeSpan ts = stw.Elapsed; //MessageBox.Show(ts.TotalMilliseconds.ToString(), "绑定数据源"); GetPageNumber(familyFiles); cbbPage.SelectedIndex = 0; //fileListView.ItemsSource = familyFileList; FileListView.ItemsSource = GetListviewItems(JumpOperation.GoHome); } #endregion #region 预览 private void BtnBrowser_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; try { var file = btn.DataContext as RvComponent; //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; PreviewFam preview = new(uiapp.Application, uiapp.ActiveUIDocument, file.Path, handler) { Owner = this }; preview.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message); LogAssists.WriteLog(ex.StackTrace); } } #endregion #region 将族加载到当前文件中 /// /// 将族加载到当前文件中。 /// /// /// private void BtnLoadFamily_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; var file = btn.DataContext as RvComponent; //((ListViewItem)video_name.ContainerFromElement((Button)sender)).Content //var file = btn.Parent; FamilyLoadOption familyLoadOption = new(); Family family = null; FamilySymbol fs = null; //FamilySymbol symbol = null; var view = doc.ActiveView; List sms = []; handler.Raise( uiapp => { using (Transaction trans = new(doc)) { trans.Start("加载族" + "-" + Path.GetFileNameWithoutExtension(file.Title)); doc.LoadFamily(file.Path, familyLoadOption, out family); var fsids = family.GetFamilySymbolIds(); if (fsids.Count > 1) //两种族类型以上时提供选择 { foreach (var id in fsids) { var name = doc.GetElement(id).Name; SymbolModel sm = new(name); sms.Add(sm); } trans.RollBack(); SelectFamilySymbol select = new(uiapp, file.Path, sms) { Owner = this }; select.ShowDialog(); } else { foreach (var id in fsids) { fs = doc.GetElement(id) as FamilySymbol; if (!fs.IsActive) { fs.Activate(); } break; } trans.Commit(); } } if (fs != null) { uiapp.ActiveUIDocument.PromptForFamilyInstancePlacement(fs); } }); } #endregion #region 路径选择 /// /// 路径选择 /// /// /// private void BtnPathChoose_Click(object sender, RoutedEventArgs e) { FolderBrowserDialog dialog = new(); if (dialog.ShowDialog()) { try { //SetConfig(dialog.SelectedPath); Properties.Settings.Default.FamilyPath2020 = dialog.SelectedPath; FileListView.ItemsSource = null; PopulateTreeView(dialog.SelectedPath); //BtnPathChoose.Content = dialog.SelectedPath; BtnPathChoose.ToolTip = dialog.SelectedPath; } catch (Exception ex) { MessageBox.Show(ex.Message); LogAssists.WriteLog(ex.StackTrace); } } } #endregion #region 根据TextBox内容,搜索所有ListViewItem /// /// 根据TextBox内容,搜索所有ListViewItem。 /// /// /// private void BtnSearch_Click(object sender, RoutedEventArgs e) { List results = []; foreach (var item in familyFiles) { var fileName = item.Name; if (fileName.Contains(TbFamilyName.Text.Trim())) { results.Add(item); } } GetPageNumber(results); tbPage.Text = pageFamilyFileList.Pagecount.ToString(); tbPageAll.Text = $"共计{results.Count}个"; FileListView.ItemsSource = GetListviewItems(JumpOperation.GoHome); } #endregion #region 获取选中的树状节点时,将该节点目录及子目录下的文件显示到ListView中 /// /// 获取选中的树状节点时,将该节点目录及子目录下的文件显示到ListView中。 /// /// /// private void DirTreeItem_Selected(object sender, RoutedEventArgs e) { //e.OriginalSource 就是TreeViewItem对象,你可以将其保存到窗体类的某个私有字段中,或者直接使用它,如下所示: var selectedItem = e.OriginalSource as TreeViewItem; //MessageBox.Show(selectedItem.Header.ToString()); familyFiles.Clear(); var currentFullPath = selectedItem.Tag.ToString(); GetFamilyFile(currentFullPath); BindListViewSource(); } #endregion #region 获取选择路径下的所有族文件 /// /// 获取选择路径下的所有族文件 /// /// private void GetFamilyFile(string fullPath) { DirectoryInfo dir = new(fullPath); try { //判断所指的文件夹/文件是否存在 if (!dir.Exists) { return; } var dirD = dir; //获取文件夹下所有文件和文件夹 var files = dirD.GetFileSystemInfos(); //对单个FileSystemInfo进行判断,如果是文件夹则进行递归操作 foreach (var FSys in files) { if (FSys is FileInfo fileInfo) { //如果是文件,进行文件操作 //获取文件所在原始路径 if (fileInfo.Extension == ".rfa") { FileInfo SFInfo = new($"{fileInfo.DirectoryName}\\{fileInfo.Name}"); familyFiles.Add(SFInfo); //SetListViewItem(SFInfo); } } else { //如果是文件夹,则进行递归调用 //string pp = FSys.Name; GetFamilyFile($"{fullPath}\\{FSys}"); } } } catch (Exception e) { MessageBox.Show(e.Message); LogAssists.WriteLog(e.StackTrace); } } #endregion #region 获取、显示页码 /// /// 获取、显示页码 /// /// private void GetPageNumber(List list) { pageFamilyFileList = new PageInfo(list, 24); List currentPageNum = []; for (var i = 0; i < pageFamilyFileList.Pagecount; i++) { currentPageNum.Add(i + 1); } tbPage.Text = pageFamilyFileList.Pagecount.ToString(); tbPageAll.Text = $"共计{familyFiles.Count}个"; cbbPage.ItemsSource = currentPageNum; } #endregion #region ListView右键加载族文件 /// /// ListView选中的所有族加载到项目中 /// /// /// private void LoadFamily_Click(object sender, RoutedEventArgs e) { handler.Raise( _ => { foreach (RvComponent item in FileListView.SelectedItems) { FamilyLoadOption familyLoadOption = new(); using Transaction trans = new(doc); trans.Start("加载族" + "-" + Path.GetFileNameWithoutExtension(item.Title)); try { doc.LoadFamily(item.Path, familyLoadOption, out var family); } catch (Exception ex) { MessageBox.Show(ex.Message); LogAssists.WriteLog(ex.StackTrace); } trans.Commit(); } }); } #endregion #region 绑定TreeView数据源 /// /// 绑定TreeView数据源 /// private void PopulateTreeView(string Path) { dirTree.Items.Clear(); TreeViewItem rootNode; DirectoryInfo info = new(Path); if (info.Exists) { rootNode = new TreeViewItem { Header = info.Name, Tag = info.FullName }; SubDirectories(info.GetDirectories(), rootNode); dirTree.Items.Add(rootNode); rootNode.IsExpanded = true; } } #endregion #region 添加目录结构到TreeView树状结构 /// /// 添加目录结构到TreeView树状结构 /// /// /// private void SubDirectories(DirectoryInfo[] subDirs, TreeViewItem nodeToAddTo) { TreeViewItem aNode; DirectoryInfo[] subSubDirs; foreach (var subDir in subDirs) { aNode = new TreeViewItem { Header = subDir.Name, Tag = subDir.FullName }; subSubDirs = subDir.GetDirectories(); if (subSubDirs.Length != 0) { SubDirectories(subSubDirs, aNode); } nodeToAddTo.Items.Add(aNode); } } #endregion #region TextBox内容清空后,恢复搜索前的页面内容。 /// /// TextBox内容清空后,恢复搜索前的页面内容。 /// /// /// private void TbFamilyName_TextChanged(object sender, TextChangedEventArgs e) { if (TbFamilyName.Text == string.Empty) { BtnSearch.IsDefault = true; if (FileListView.ItemsSource != null) { GetPageNumber(familyFiles); pageFamilyFileList.CurrentIndex = cbbPage.SelectedIndex + 1; FileListView.ItemsSource = GetListviewItems(JumpOperation.GoAny); } } } #endregion #region 全局变量 private readonly UIApplication uiapp; //Autodesk.Revit.ApplicationServices.Application app; private readonly Document doc; private PageInfo pageFamilyFileList; //分页族文件列表,可作为搜索的分页族文件列表 private readonly List familyFiles = []; //所有族文件列表 #endregion #region 构造函数 public LocalFamsLibWin(UIApplication uiapp) { //Resources.MergedDictionaries.Add(new ResourceDictionary //{ // Source = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml") //}); //Resources.MergedDictionaries.Add(new ResourceDictionary //{ // Source = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml") //}); //Resources.MergedDictionaries.Add(new ResourceDictionary //{ // Source = new Uri("pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Blue.xaml") //}); //Resources.MergedDictionaries.Add(new ResourceDictionary //{ // Source = new Uri("pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml") //}); //Assembly.LoadFile(@"F:\OneDrive\Revit二次开发\Revit Dev\FamilyTools\bin\Debug\MahApps.Metro.IconPacks.dll"); InitializeComponent(); doc = uiapp.ActiveUIDocument.Document; //this.app = uiapp.Application; this.uiapp = uiapp; #if REVIT2018 var familyPath = Properties.Settings.Default.FamilyPath2018; #elif REVIT2019 var familyPath = Properties.Settings.Default.FamilyPath2019; #elif REVIT2020 var familyPath = Properties.Settings.Default.FamilyPath2020; #endif PopulateTreeView(familyPath); //BtnPathChoose.Content = familyPath; BtnPathChoose.ToolTip = familyPath; } #endregion #region 将路径下的族文件名称、缩略图用ListViewItem包装起来(最耗时) //private void GetListViewSource(FileInfo SFInfo) //{ //ListViewItem listViewItem = new ListViewItem(); //Thickness thickness = new Thickness(); //thickness.Top = 5; //thickness.Bottom = 5; //thickness.Left = 5; //thickness.Right = 5; //System.Windows.Media.Color color = (System.Windows.Media.Color)System.Windows.Media.ColorToBrushConverter.ConvertFromString("#FFF0F0F0"); //StackPanel sp = new StackPanel //{ // //Background = new System.Windows.Media.SolidColorBrush(color), // HorizontalAlignment = HorizontalAlignment.Center, // VerticalAlignment = VerticalAlignment.Center, // Margin = thickness, //}; //TextBlock tb = new TextBlock //{ // Text = Path.GetFileNameWithoutExtension(SFInfo.ToString()), // Width = 64, // Height = 15, // TextAlignment = TextAlignment.Center, // TextWrapping = TextWrapping.WrapWithOverflow //}; //System.Drawing.Bitmap bmp = WindowsThumbnailProvider.GetThumbnail(SFInfo.ToString(), 64, 64, ThumbnailOptions.None); //System.Windows.Media.Imaging.BitmapSource bm = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); //Image image = new Image //{ // Source = bm, // Stretch = System.Windows.Media.Stretch.Uniform, // Height = 64, // Width = 64 //}; //sp.Children.Add(image); //sp.Children.Add(tb); //listViewItem.Content = sp; ////listViewItem.ToolTip = SFInfo.ToString(); //listViewItem.ToolTip = Path.GetFileNameWithoutExtension(SFInfo.ToString()); //listViewItem.Tag = SFInfo; //familyFileList.Add(listViewItem); //} #endregion #region 页面切换按钮 private void BtnHome_Click(object sender, RoutedEventArgs e) { if (FileListView.ItemsSource != null) { FileListView.ItemsSource = GetListviewItems(JumpOperation.GoHome); cbbPage.SelectedIndex = pageFamilyFileList.CurrentIndex - 1; } } private void BtnPrevious_Click(object sender, RoutedEventArgs e) { if (FileListView.ItemsSource != null) { FileListView.ItemsSource = GetListviewItems(JumpOperation.GoPrePrevious); cbbPage.SelectedIndex = pageFamilyFileList.CurrentIndex - 1; } } private void BtnNext_Click(object sender, RoutedEventArgs e) { if (FileListView.ItemsSource != null) { FileListView.ItemsSource = GetListviewItems(JumpOperation.GoNext); cbbPage.SelectedIndex = pageFamilyFileList.CurrentIndex - 1; } } private void BtnEnd_Click(object sender, RoutedEventArgs e) { if (FileListView.ItemsSource != null) { FileListView.ItemsSource = GetListviewItems(JumpOperation.GoEnd); cbbPage.SelectedIndex = pageFamilyFileList.CurrentIndex - 1; } } private void CbbPage_DropDownClosed(object sender, EventArgs e) { if (FileListView.ItemsSource != null) { pageFamilyFileList.CurrentIndex = cbbPage.SelectedIndex + 1; FileListView.ItemsSource = GetListviewItems(JumpOperation.GoAny); } } #endregion #region 浏览族文件 private void OpenFile_Click(object sender, RoutedEventArgs e) { foreach (RvComponent item in FileListView.SelectedItems) { var filePath = item.Path; WinDialogAssists.OpenFolderAndSelectFile(filePath); } } #endregion } }