优化更新

This commit is contained in:
GG Z
2025-02-10 20:53:40 +08:00
parent 83b846f15f
commit 9696128f03
62 changed files with 2567 additions and 1608 deletions

3
.filenesting.json Normal file
View File

@@ -0,0 +1,3 @@
{
"help":"https://go.microsoft.com/fwlink/?linkid=866610"
}

View File

@@ -11,7 +11,7 @@
<PackageReference Include="CommunityToolkit.HighPerformance" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.2" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="OpenAI" Version="2.0.0" />
<!--<PackageReference Include="OpenAI" Version="2.0.0" />-->
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
</ItemGroup>
</Project>

View File

@@ -9,10 +9,13 @@ using System.Threading.Tasks;
using ACadSharp.Entities;
using CommunityToolkit.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CSMath;
using OpenAI.Chat;
//using OpenAI.Chat;
namespace ConsoleApp
{
@@ -21,10 +24,17 @@ namespace ConsoleApp
static void Main(string[] args)
{
//TEST();
var re = new Receive();
var p = new Person();
var value = new ValueChangedMessage<Person>(p);
var propChange = new PropertyChangedMessage<string>(new Program(),nameof(Person.Name),"bob","jenny");
ChatClient client = new ChatClient("gpt-4o", Environment.GetEnvironmentVariable("OPEN_API_KEY"));
ChatCompletion completion = client.CompleteChat("say 'this is a test.'");
Console.WriteLine($"[ASSISTANT]:{completion.Content[0].Text}");
WeakReferenceMessenger.Default.Send(propChange);
WeakReferenceMessenger.Default.Send(value);
WeakReferenceMessenger.Default.Send(p);
//ChatClient client = new ChatClient("gpt-4o", Environment.GetEnvironmentVariable("OPEN_API_KEY"));
//ChatCompletion completion = client.CompleteChat("say 'this is a test.'");
//Console.WriteLine($"[ASSISTANT]:{completion.Content[0].Text}");
}
private static void TEST()
@@ -125,4 +135,36 @@ namespace ConsoleApp
//}
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public partial class Receive:ObservableRecipient,IRecipient<ValueChangedMessage<Person>>,IRecipient<Person>,IRecipient<PropertyChangedMessage<string>>
{
public Receive()
{
IsActive = true;
//WeakReferenceMessenger.Default
// .Register<Person>(
// this,
// (r, m) =>
// {
// });
}
void IRecipient<ValueChangedMessage<Person>>.Receive(ValueChangedMessage<Person> message)
{
}
void IRecipient<Person>.Receive(Person message)
{
}
void IRecipient<PropertyChangedMessage<string>>.Receive(PropertyChangedMessage<string> message)
{
}
}
}

View File

@@ -0,0 +1,153 @@
using System;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Nice3point.Revit.Toolkit.External;
using Sai.Toolkit.Revit.Assist;
using Sai.Toolkit.Revit.Helpers;
namespace RvAddinTest;
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class AddWallTypeParam : ExternalCommand
{
public Result Executex(ExternalCommandData commandData, ref string message, ElementSet elements)
{
//程序UI界面
UIApplication uiapp = commandData.Application;
//获取元素(选择) 显示元素 视图(活动视图)管理(对象)
UIDocument uidoc = uiapp.ActiveUIDocument;
//程序
Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
//获取位置和场地 视图(多个视图)管理 获取元素Revit 项目里的全部元素)
Document doc = uidoc.Document;
//获取所有打开文档
DocumentSet docset = uiapp.Application.Documents;
//当前视图
View view = doc.ActiveView;
#region FilterExecute
var walls = new FilteredElementCollector(doc).OfClass(typeof(Wall)).ToElements();
using (Transaction trans = new Transaction(doc, "default"))
{
try
{
trans.Start();
//Do Something.
trans.Commit();
}
catch (Exception ex)
{
message = ex.Message;
if (trans.GetStatus() == TransactionStatus.Started)
{
trans.RollBack();
}
return Result.Failed;
}
}
#endregion FilterExecute
#region RepeatExecute
bool isCoutine = true;
using (Transaction trans = new Transaction(doc, "default"))
{
try
{
while (isCoutine)
{
try
{
trans.Start();
//do something.
trans.Commit();
}
catch (Exception)
{
trans.Commit();
return Result.Succeeded;
}
}
}
catch (Autodesk.Revit.Exceptions.OperationCanceledException)
{
if (trans.GetStatus() == TransactionStatus.Started)
{
trans.Commit();
}
}
catch (Exception ex)
{
message = ex.Message;
if (trans.GetStatus() == TransactionStatus.Started)
{
trans.Commit();
}
return Result.Succeeded;
}
}
#endregion RepeatExecute
#region SelectExecute
using (Transaction trans = new Transaction(doc, "default"))
{
try
{
Reference refer = uidoc.Selection.PickObject(ObjectType.Element, "请选择XXX");
Element e = uidoc.Document.GetElement(refer);
trans.Start();
//Do Something.
trans.Commit();
}
catch (Autodesk.Revit.Exceptions.OperationCanceledException ex)
{
if (trans.GetStatus() == TransactionStatus.Started)
{
trans.Commit();
}
return Result.Succeeded;
}
catch (Exception ex)
{
message = ex.Message;
if (trans.GetStatus() == TransactionStatus.Started)
{
trans.RollBack();
}
return Result.Failed;
}
}
#endregion SelectExecute
return Result.Succeeded;
}
public override void Execute()
{
Document.Invoke(
ts =>
{
var file = ParameterAssist.OpenSharedParametersFile(Application);
var group = file.Groups.get_Item("Atkore");
var definition = group.Definitions.get_Item("test");
var categories = Application.Create.NewCategorySet();
categories.Insert(Category.GetCategory(Document, BuiltInCategory.OST_Walls));
var newIB = Application.Create.NewTypeBinding(categories);
var b = Document.ParameterBindings.ReInsert(definition, newIB);
});
}
}

View File

@@ -1,57 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Nice3point.Revit.Toolkit.External;
using Nice3point.Revit.Toolkit.Utils;
using Sai.Toolkit.Revit.Assist;
namespace RvAddinTest;
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
internal class CorrectSlope : ExternalCommand
{
public override void Execute()
{
var ids = UiDocument.Selection.GetElementIds();
Document.Modify(
set => set.Transaction).Commit((doc, t) =>
{
foreach (var id in ids)
{
var elem = Document.GetElement(id);
if (elem is MEPCurve mep)
{
var loc = mep.GetCurve() as Line;
var x = Math.Round(loc.Direction.X);
var y = Math.Round(loc.Direction.Y);
var z = Math.Round(loc.Direction.Z);
//if (Math.Abs(x) < 10E-5)
//{
// x = 0;
//}
//if (Math.Abs(y) < 10E-5)
//{
// y = 0;
//}
//if (Math.Abs(z) < 10E-5)
//{
// z = 0;
//}
var dir = new XYZ(x, y, z);
var endPoint = loc.Origin + dir * loc.Length;
var li = Line.CreateBound(loc.Origin, endPoint);
var locx = mep.GetLocationCurve();
locx.Curve = li;
}
}
});
}
}

View File

@@ -1,24 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Nice3point.Revit.Toolkit.External.Handlers;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
namespace RvAddinTest;
/// <summary>
/// CreateWindow.xaml 的交互逻辑
@@ -52,21 +38,6 @@ public partial class CreateWindow
catch (Autodesk.Revit.Exceptions.OperationCanceledException)
{
}
//uiapp.Application.DocumentChanged -= Application_DocumentChanged;
});
}
private void Application_DocumentChanged(object sender, Autodesk.Revit.DB.Events.DocumentChangedEventArgs e)
{
if (e.GetAddedElementIds().Count == 1)
{
var id = e.GetAddedElementIds().FirstOrDefault();
var elem = e.GetDocument().GetElement(id);
if (elem is FamilyInstance ins && ins.Symbol.FamilyName.Contains("铜球阀"))
{
}
}
}
}

View File

@@ -1,105 +0,0 @@
using System;
using System.Reflection;
using System.Windows;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Sai.Toolkit.Revit.Assist;
namespace RvAddinTest;
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class DeleteCmd : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
//程序UI界面
var uiapp = commandData.Application;
//获取元素(选择) 显示元素 视图(活动视图)管理(对象)
var uidoc = uiapp.ActiveUIDocument;
//程序
var app = uiapp.Application;
//获取位置和场地 视图(多个视图)管理 获取元素Revit 项目里的全部元素)
var doc = uidoc.Document;
//获取所有打开文档
var docset = uiapp.Application.Documents;
//当前视图
var view = doc.ActiveView;
#region FilterExecute
//if (doc.IsFamilyDocument)
//{
// var manager = doc.FamilyManager;
// using (var trans = new Transaction(doc, "default"))
// {
// try
// {
// trans.Start();
// var param = manager.AddParameter(
// "测试",
// BuiltInParameterGroup.PG_ADSK_MODEL_PROPERTIES,
// ParameterType.Number,
// true);
// trans.Commit();
// }
// catch (Exception ex)
// {
// throw ex;
// }
// }
//}
var docType = doc.GetType();
var method = docType.GetMethod("GetUnusedFamilies", BindingFlags.NonPublic | BindingFlags.Instance);
if (method != null)
{
var unusedFamilyIds = method.Invoke(doc, null) as ISet<ElementId>;
using (var trans = new Transaction(doc, nameof(DeleteCmd)))
{
trans.Start();
//foreach (var id in unusedFamilyIds)
//{
// doc.Delete(id);
//}
MessageBox.Show(unusedFamilyIds.Count.ToString());
trans.Commit();
}
}
//var instances = new FilteredElementCollector(doc).OfClass(typeof(Pipe)).ToElements();
//using (Transaction trans = new Transaction(doc, "default"))
//{
// try
// {
// trans.Start();
// var ids = new List<ElementId>();
// foreach (Pipe pipe in instances)
// {
// if (Math.Abs(pipe.Diameter - 32 / 304.8) < 10E-5)
// {
// ids.Add(pipe.Id);
// }
// }
// //doc.Delete(ids);
// uidoc.Selection.SetElementIds(ids);
// //Do Something.
// trans.Commit();
// }
// catch (Exception ex)
// {
// message = ex.Message;
// if (trans.GetStatus() == TransactionStatus.Started)
// {
// trans.RollBack();
// }
// return Result.Failed;
// }
//}
#endregion FilterExecute
return Result.Succeeded;
}
}

View File

@@ -1,28 +1,15 @@
using System.Diagnostics;
using System.IO;
using System.Management.Instrumentation;
using System.Text;
using System.Windows;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using eTransmitForRevitDB;
using Microsoft.Win32;
using Nice3point.Revit.Toolkit.External;
using Nice3point.Revit.Toolkit.Utils;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using Sai.Toolkit.Revit.Assist;
using Sai.Toolkit.Revit.Helpers;
namespace RvAddinTest;
@@ -30,98 +17,169 @@ namespace RvAddinTest;
[Regeneration(RegenerationOption.Manual)]
internal class FluentAddin : ExternalCommand
{
public static bool Purge(Document doc)
/// <summary>
/// 设备类型是否为空
/// </summary>
private void CableTrayCheck()
{
var eTransmitUpgradeOMatic = new eTransmitUpgradeOMatic(doc.Application);
//var list = Document.OfClass<CableTray>().Cast<CableTray>().ToList();
var list = Document.OfCollector().OfCategory(BuiltInCategory.OST_CableTrayFitting).WhereElementIsNotElementType().ToList();
var ids = new List<ElementId>();
foreach (var item in list)
{
var elem = Document.GetElement(item.GetTypeId());
var value = item.get_Parameter(BuiltInParameter.RBS_CTC_SERVICE_TYPE).AsString();
if (string.IsNullOrEmpty(value))
{
ids.Add(item.Id);
continue;
}
if (elem.Name.Contains(value))
{
continue;
}
ids.Add(item.Id);
var result = eTransmitUpgradeOMatic.purgeUnused(doc);
}
UiDocument.Selection.SetElementIds(ids);
}
return result == UpgradeFailureType.UpgradeSucceeded;
/// <summary>
/// 修改名称
/// </summary>
private void ModifyName()
{
Document.Modify(set => set.Transaction)
.Commit(
(d, t) =>
{
//var point = Point.Create(new XYZ(10,10,10), new ElementId(1236));
//Document.CreateTransientElements([point]);
var fittings = Document
.OfClass<FamilySymbol>()
.WhereElementIsElementType().Cast<FamilySymbol>();
//var fittings = Document.OfCollector()
// .OfCategory(BuiltInCategory.OST_DuctFitting)
// .WhereElementIsElementType().Cast<FamilySymbol>();
foreach (var item in fittings)
{
//point=Point.Create(XYZ.BasisX);
//if (item.Name.StartsWith("DN"))
//{
// item.Name = item.FamilyName + "-" + item.Name;
//}
if (item.Name == "标准" || item.Name == "默认")
{
item.Name = item.FamilyName;
}
//try
//{
// item.get_Parameter(BuiltInParameter.ALL_MODEL_URL).Set("");
// item.get_Parameter(BuiltInParameter.ALL_MODEL_DESCRIPTION).Set("");
//}
//catch (Exception)
//{
// MessageBox.Show(item.Name);
//}
}
});
}
/// <summary>
/// 坡度检查
/// </summary>
private void SlopeCheck()
{
var mepCurves = ActiveView.OfClass<MEPCurve>();
var ids = new List<ElementId>();
foreach (var mepCurve in mepCurves)
{
var p1 = mepCurve.get_Parameter(BuiltInParameter.RBS_START_OFFSET_PARAM).AsDouble();
var p2 = mepCurve.get_Parameter(BuiltInParameter.RBS_END_OFFSET_PARAM).AsDouble();
var l = mepCurve.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH).AsDouble();
var sin = Math.Abs(p1 - p2) / l;
var radian = Math.Asin(sin);
var slope = Math.Tan(radian);
var isError = slope is (> 10E-6 and < 0.25) || (slope > Math.PI && Math.Abs(radian - Math.PI / 2) > 10E-6);
if (isError)
{
Debug.WriteLine($"角度:{radian}");
Debug.WriteLine($"坡度:{slope}");
ids.Add(mepCurve.Id);
}
}
UiDocument.Selection.SetElementIds(ids);
}
public override void Execute()
{
//var elemIds = Document.OfAllModelElements().Select(e=>e.Id).ToList();
var textTypes = Document.OfClass<TextNoteType>().ToList();
var accessoryTypes = Document.OfClass<FamilySymbol>().OfCategory(BuiltInCategory.OST_PipeAccessory).WhereElementIsElementType().ToList();
var filledRegionTypes = Document.OfClass<FilledRegionType>().ToList();
var materialToClean = Document.OfClass<Material>().Where(m => m.Name.StartsWith("渲染材质")).Select(e => e.Id).ToList();
Application.DocumentChanged += Application_DocumentChanged;
Document.Invoke(
ts =>
{
//var id = UiDocument.Selection.GetElementIds().FirstOrDefault();
//var elem = Document.GetElement(id);
//var typeId = elem.GetTypeId();
//CleanImportLinePattern(Document);
//try
//{
// foreach (var item in accessoryTypes)
// {
// if (item is FamilySymbol symbol)
// {
// symbol.Name = $"{symbol.FamilyName}-{symbol.Name}";
// }
// }
//}
//catch (Exception ex)
//{
// throw ex;
//}
//foreach (var type in textTypes)
//{
// CleanTextTypes(type);
//}
//foreach (var item in filledRegionTypes)
//{
// if (item is FilledRegionType type)
// {
// var foreFillType = type.ForegroundPatternId;
// var foreFillColor = type.ForegroundPatternColor;
// var backFillType = type.BackgroundPatternId;
// var backFillColor = type.BackgroundPatternColor;
// }
//}
//Document.Delete(materialToClean);
});
//string input = type.Name;
//int lastDashIndex = input.LastIndexOf('-');
//if (lastDashIndex != -1)
//{
// string result = input.Substring(0, lastDashIndex);
// type.Name = result;
//}
//UiDocument.Selection.SetElementIds(elemIds);
var refer=UiDocument.Selection.PickObject(ObjectType.Element);
var elem=Document.GetElement(refer);
var conn=elem.GetConnectors().Cast<Connector>().Where(c=>c.IsConnected).FirstOrDefault();
var connto = conn.GetConnectedConnector();
Debug.WriteLine("管线:");
Debug.WriteLine(conn.CoordinateSystem.BasisX);
Debug.WriteLine(conn.CoordinateSystem.BasisY);
Debug.WriteLine(conn.CoordinateSystem.BasisZ);
Debug.WriteLine("管件:");
Debug.WriteLine(connto.CoordinateSystem.BasisX);
Debug.WriteLine(connto.CoordinateSystem.BasisY);
Debug.WriteLine(connto.CoordinateSystem.BasisZ);
//StringBuilder sb = new StringBuilder();
//var n = 1;
//foreach (var item in elems)
//var refer = UiDocument.Selection.PickObject(ObjectType.Element);
//var elem = Document.GetElement(refer);
//var conn = elem.GetConnectors().Cast<Connector>().Where(c => c.IsConnected).FirstOrDefault();
//var docType = Document.GetType();
//var method = docType.GetMethod("GetUnusedFamilies", BindingFlags.NonPublic | BindingFlags.Instance);
//if (method != null)
//{
// sb.Append(n +":"+ item.Name + item.Id.ToString()+"new");
// n++;
// var unusedFamilyIds = method.Invoke(Document, null) as ISet<ElementId>;
//}
//MessageBox.Show(sb.ToString());
//StringBuilder sb = new();
//var regions = Document.OfCollector().OfCategory(BuiltInCategory.OST_DetailComponents).WhereElementIsNotElementType().ToList();
//sb.AppendLine(regions.Count.ToString());
//regions.ToList().ForEach(f => sb.AppendLine($"{f.Id}"));
//MessageBox.Show(sb.ToString());
//UiDocument.Selection.SetElementIds(elements);
#region MyRegion
//OpenFileDialog openFileDialog = new OpenFileDialog() { Multiselect = true, Filter = "Revit文件|*.rvt" };
//if (openFileDialog.ShowDialog() == false)
//{
// return;
//};
//foreach (var file in openFileDialog.FileNames)
//{
// var doc = UiApplication.Application.OpenDocumentFile(file);
// var options = new SaveAsOptions()
// {
// Compact = true,
// OverwriteExistingFile = true,
// MaximumBackups = 3,
// };
// try
// {
// var ids = doc.OfCollector().OfCategory(BuiltInCategory.OST_Lines).Select(e => e.Id).ToList();
// doc.Modify(set => set.Transaction)
// .Commit(
// (doc, t) =>
// {
// doc.Delete(ids);
// });
// for (var i = 0; i < 5; i++)
// {
// Purge(doc);
// }
// //doc.SaveAs(file, options);
// doc.Close(true);
// }
// catch (Exception)
// {
// doc.Close();
// }
//}
//MessageBox.Show("处理完成");
#endregion
//var b = Document.ActiveView.ViewTemplateId == null;
//MessageExtensions.ShowMessage(b.ToString());
//var h = Document.ActiveView
// .OfClass<Duct>()
// .Cast<Duct>()
// .Where(
// d =>
// d.ConnectorManager.Connectors.OfType<Connector>().FirstOrDefault().Shape
// != ConnectorProfileType.Round
// )
// .Max(d => d.Height);
//Document.Invoke
#region RegionName
//OpenFileDialog dialog = new() { Filter = "Revit(*.rvt)|*.rvt", Multiselect = true };
//dialog.ShowDialog();
@@ -154,162 +212,126 @@ internal class FluentAddin : ExternalCommand
// //var importInstance = doc.GetElement(refer) as ImportInstance;
// //ConvertToMassCurve(importInstance);
// });
//DebugAssist.CreateTransientGeometries(Document,Point.Create(Document.ActiveView.CropBox.Transform.Origin));
//DebugAssist.CreateTransientGeometries(Document,Point.Create(Document.ActiveView.CropBox.Min));
//DebugAssist.CreateTransientGeometries(Document,Point.Create(Document.ActiveView.CropBox.Max));
//var mepCurve = UiDocument.SelectObject<MEPCurve>();
//if (mepCurve != null)
//{
// var list = new List<ElementId>();
// mepCurve.GetAllConnectedElements(list);
// UiDocument.Selection.SetElementIds(list);
//}
}
private void GetDiffSystemFittings()
private void Application_DocumentChanged(object sender, Autodesk.Revit.DB.Events.DocumentChangedEventArgs e)
{
var elbows = Document.OfClass<FamilyInstance>()
.OfCategory(BuiltInCategory.OST_PipeFitting)
.Cast<FamilyInstance>()
.Where(fi => fi.MEPModel is MechanicalFitting fitting && fitting.PartType == PartType.Elbow);
var elementId = ElementId.InvalidElementId;
foreach (var elbow in elbows)
StringBuilder sb = new StringBuilder();
var doc = e.GetDocument();
bool b = true;
foreach (var idAdd in e.GetAddedElementIds())
{
if (elbow.Id.IntegerValue == 9437638)
if (b)
{
sb.AppendLine();
sb.AppendLine("新增的元素");
b = !b;
}
var elem = doc.GetElement(idAdd);
var typeId = elem.GetTypeId();
if (typeId != ElementId.InvalidElementId)
{
var type = doc.GetElement(idAdd);
sb.Append($"类型名称:{type.Name}");
}
sb.Append($"元素ID{elem.Id};元素名称:{elem.Name} ");
}
b = true;
foreach (var idDel in e.GetDeletedElementIds())
{
if (b)
{
sb.AppendLine();
sb.AppendLine("删除的元素");
b = !b;
}
var elem = doc.GetElement(idDel);
var typeId = elem.GetTypeId();
if (typeId != ElementId.InvalidElementId)
{
var type = doc.GetElement(idDel);
sb.Append($"类型名称:{type.Name}");
}
sb.Append($"元素ID{elem.Id};元素名称:{elem.Name} ");
}
b = true;
foreach (var idModify in e.GetModifiedElementIds())
{
if (b)
{
sb.AppendLine();
sb.AppendLine("修改的元素");
b = !b;
}
var elem = doc.GetElement(idModify);
var typeId = elem.GetTypeId();
if (typeId != ElementId.InvalidElementId)
{
var type = doc.GetElement(idModify);
sb.Append($"类型名称:{type.Name}");
}
sb.Append($"元素ID{elem.Id};元素名称:{elem.Name} ");
}
if (sb.Length > 0)
{
MessageBox.Show(sb.ToString());
}
}
/// <summary>
/// 清理导入的线型图案
/// </summary>
/// <param name="doc"></param>
private static void CleanImportLinePattern(Document doc)
{
var templates = doc.OfClass<LinePatternElement>()
.Cast<LinePatternElement>()
.Where(e => e.Name.StartsWith("IMPORT"))
.Select(e => e.Id).ToList();
doc.Delete(templates);
}
/// <summary>
/// 清理文字样式
/// </summary>
/// <param name="type"></param>
private void CleanTextTypes(Element type)
{
if (type is TextNoteType textNoteType)
{
try
{
var connectors = elbow.GetConnectors();
var connector1 = connectors.OfType<Connector>().ElementAt(0);
var connector2 = connectors.OfType<Connector>().ElementAt(1);
var system1 = connector1.AllRefs.OfType<Connector>().FirstOrDefault(c => c.Owner.Id != elbow.Id).MEPSystem;
var system2 = connector2.AllRefs.OfType<Connector>().FirstOrDefault(c => c.Owner.Id != elbow.Id).MEPSystem;
//MEPSystem tempSystem = null;
//foreach (Connector conn in connectors)
//{
// foreach (Connector item in conn.AllRefs)
// {
// if (tempSystem==null)
// {
// tempSystem = item.MEPSystem;
// continue;
// }
// if (tempSystem==item.MEPSystem)
// {
// continue;
// }
// if (tempSystem.Name)
// {
// }
// }
//}
if (system1.Name != system2.Name)
var font = textNoteType.get_Parameter(BuiltInParameter.TEXT_FONT).AsString();
var size = textNoteType.get_Parameter(BuiltInParameter.TEXT_SIZE).AsValueString().TrimEnd('m');
var dSize = Math.Round(Convert.ToDouble(size), 1, MidpointRounding.AwayFromZero);
if (dSize < 0.23)
{
elementId = elbow.Id;
break;
return;
}
textNoteType.get_Parameter(BuiltInParameter.TEXT_SIZE).SetValueString(dSize.ToString());
var scale = textNoteType.get_Parameter(BuiltInParameter.TEXT_WIDTH_SCALE).AsValueString();
//var color = textNoteType.get_Parameter(BuiltInParameter.LINE_COLOR).AsInteger();
var name = $"{font}-{dSize}mm-{scale}";
var textTypes = Document.OfClass<TextNoteType>().ToList();
var isExist = textTypes.FirstOrDefault(t => t.Name == name);
if (isExist != null)
{
var texts = Document.OfClass<TextNote>().Where(e => e.GetTypeId() == textNoteType.Id).ToList();
texts.ForEach(e => e.ChangeTypeId(isExist.Id));
Document.Regenerate();
Document.Delete(textNoteType.Id);
}
else
{
textNoteType.Name = name;
}
}
catch (Exception)
{
//MessageBox.Show(elbow.Id.ToString());
continue;
throw;
}
}
if (elementId != ElementId.InvalidElementId)
{
UiDocument.Selection.SetElementIds([elementId]);
}
}
private void ModifyName()
{
Document.Modify(set => set.Transaction)
.Commit(
(d, t) =>
{
//var point = Point.Create(new XYZ(10,10,10), new ElementId(1236));
//Document.CreateTransientGeometries([point]);
var fittings = Document
.OfClass<FamilySymbol>()
.WhereElementIsElementType().Cast<FamilySymbol>();
//var fittings = Document.OfCollector()
// .OfCategory(BuiltInCategory.OST_DuctFitting)
// .WhereElementIsElementType().Cast<FamilySymbol>();
foreach (var item in fittings)
{
//point=Point.Create(XYZ.BasisX);
//if (item.Name.StartsWith("DN"))
//{
// item.Name = item.FamilyName + "-" + item.Name;
//}
if (item.Name == "标准")
{
item.Name = item.FamilyName;
}
//try
//{
// item.get_Parameter(BuiltInParameter.ALL_MODEL_URL).Set("");
// item.get_Parameter(BuiltInParameter.ALL_MODEL_DESCRIPTION).Set("");
//}
//catch (Exception)
//{
// MessageBox.Show(item.Name);
//}
}
});
}
private void CableTrayCheck()
{
//var list = Document.OfClass<CableTray>().Cast<CableTray>().ToList();
var list = Document.OfCollector().OfCategory(BuiltInCategory.OST_CableTrayFitting).WhereElementIsNotElementType().ToList();
var ids = new List<ElementId>();
foreach (var item in list)
{
var elem = Document.GetElement(item.GetTypeId());
var value = item.get_Parameter(BuiltInParameter.RBS_CTC_SERVICE_TYPE).AsString();
if (string.IsNullOrEmpty(value))
{
ids.Add(item.Id);
continue;
}
if (elem.Name.Contains(value))
{
continue;
}
ids.Add(item.Id);
}
UiDocument.Selection.SetElementIds(ids);
}
private void SlopeCheck()
{
var mepCurves = ActiveView.OfClass<MEPCurve>();
var ids = new List<ElementId>();
foreach (var mepCurve in mepCurves)
{
var p1 = mepCurve.get_Parameter(BuiltInParameter.RBS_START_OFFSET_PARAM).AsDouble();
var p2 = mepCurve.get_Parameter(BuiltInParameter.RBS_END_OFFSET_PARAM).AsDouble();
var l = mepCurve.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH).AsDouble();
var sin = Math.Abs(p1 - p2) / l;
var radian = Math.Asin(sin);
var slope = Math.Tan(radian);
var isError = slope is (> 10E-6 and < 0.25) || (slope > Math.PI && Math.Abs(radian - Math.PI / 2) > 10E-6);
if (isError)
{
Debug.WriteLine($"角度:{radian}");
Debug.WriteLine($"坡度:{slope}");
ids.Add(mepCurve.Id);
}
}
UiDocument.Selection.SetElementIds(ids);
}
}

View File

@@ -1,28 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using ACadSharp.Entities;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Plumbing;
using CSMath;
using XYZ = Autodesk.Revit.DB.XYZ;
using Nice3point.Revit.Toolkit.External;
using Nice3point.Revit.Toolkit.Options;
using Nice3point.Revit.Toolkit.Utils;
using Line = Autodesk.Revit.DB.Line;
using Autodesk.Revit.DB.Plumbing;
using System.IO;
using System.Collections.ObjectModel;
using Sai.Toolkit.Revit.Assist;
using Microsoft.Win32;
using Sai.Toolkit.Core.Helpers;
using Nice3point.Revit.Toolkit.External;
using System;
using System.IO;
using System.Linq;
using System.Text;
using Line = Autodesk.Revit.DB.Line;
using XYZ = Autodesk.Revit.DB.XYZ;
namespace RvAddinTest
{
@@ -63,7 +59,6 @@ namespace RvAddinTest
// }
//}
//var conns = elem.MEPModel.ConnectorManager.UnusedConnectors.OfType<Connector>().FirstOrDefault();
}
private void GASCreator()
@@ -123,7 +118,7 @@ namespace RvAddinTest
var locXY = line.Vertices.FirstOrDefault().Location;
var firstPoint = XYToRevitXYZ(locXY);
var lastPoint = XYToRevitXYZ(line.Vertices.LastOrDefault().Location);
if (firstPoint.DistanceTo(lastPoint)<Application.ShortCurveTolerance)
if (firstPoint.DistanceTo(lastPoint) < Application.ShortCurveTolerance)
{
continue;
}

View File

@@ -1,48 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
namespace RvAddinTest
{
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
internal class HideElementsAllViews : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
//程序UI界面
UIApplication uiapp = commandData.Application;
//获取元素(选择) 显示元素 视图(活动视图)管理(对象)
UIDocument uidoc = uiapp.ActiveUIDocument;
//程序
Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
//获取位置和场地 视图(多个视图)管理 获取元素Revit 项目里的全部元素)
Document doc = uidoc.Document;
//获取所有打开文档
DocumentSet docset = uiapp.Application.Documents;
//当前视图
View view = doc.ActiveView;
IEnumerable<View> col = new FilteredElementCollector(doc).OfClass(typeof(View))
.WhereElementIsNotElementType()
.Cast<View>()
.Where(v => !v.IsTemplate);
using (Transaction ts = new Transaction(doc, "隐藏"))
{
ts.Start();
foreach (View v in col)
{
v.HideElements(uidoc.Selection.GetElementIds());
}
ts.Commit();
}
return Result.Succeeded;
}
}
}

View File

@@ -1,16 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Nice3point.Revit.Toolkit.External;
using Nice3point.Revit.Toolkit.Options;
using Nice3point.Revit.Toolkit.Utils;
namespace RvAddinTest
{

View File

@@ -1,57 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Sai.Toolkit.Revit.Assist;
namespace RvAddinTest;
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
internal class ModifySystemTypeCmd : IExternalCommand
{
/// <summary>
/// 获取标高
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public ElementId GetLevelId(Element model)
{
// 定义需要检查的参数列表
var parametersToCheck = new BuiltInParameter[]
{
BuiltInParameter.WALL_BASE_CONSTRAINT, // 墙
BuiltInParameter.SCHEDULE_BASE_LEVEL_PARAM, // 柱子标高
BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM, // 梁标高
BuiltInParameter.STAIRS_BASE_LEVEL_PARAM, // 楼梯标高
BuiltInParameter.INSTANCE_ELEVATION_PARAM, // 族实例明细表标高
BuiltInParameter.ROOF_CONSTRAINT_LEVEL_PARAM,//屋顶
BuiltInParameter.INSTANCE_SCHEDULE_ONLY_LEVEL_PARAM,// 族实例明细表标高
BuiltInParameter.RBS_START_LEVEL_PARAM// 管线标高
};
// 依次检查每个参数
foreach (var param in parametersToCheck)
{
var baseLevelId = model.get_Parameter(param)?.AsElementId();
if (baseLevelId != ElementId.InvalidElementId && baseLevelId != null)
{
return baseLevelId;
}
}
//最后检查楼板或族基准标高
return model.LevelId;
}
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
//程序UI界面
@@ -178,21 +134,6 @@ internal class ModifySystemTypeCmd : IExternalCommand
//}
#region RegionName
//var templates = doc.OfClass<LinePatternElement>()
// .Cast<LinePatternElement>()
// .Where(e => e.Name.StartsWith("IMPORT"))
// .Select(e => e.Id).ToList();
//using (var trans = new Transaction(doc, nameof(ModifySystemTypeCmd)))
//{
// trans.Start();
// doc.Delete(templates);
// //foreach (var id in uidoc.Selection.GetElementIds())
// //{
// // var elem = doc.GetElement(id);
// // elem.ChangeTypeId(systemType.Id);
// //}
// trans.Commit();
//}
#endregion
try
{
@@ -230,4 +171,5 @@ internal class ModifySystemTypeCmd : IExternalCommand
}
return Result.Succeeded;
}
}

View File

@@ -1,4 +1,5 @@
using System.Text;
using System.Windows;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
@@ -162,7 +163,7 @@ public class RemoveParamCmd : ExternalCommand
ts.Commit();
}
famdoc.LoadFamily(Document, new FamilyLoadOption());
famdoc.LoadFamily(Document);
famdoc.Close(false);
}
}

View File

@@ -1,14 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using EPPlus.Core.Extensions;
@@ -22,92 +17,103 @@ namespace RvAddinTest;
[Regeneration(RegenerationOption.Manual)]
internal class ReplaceCode : ExternalCommand
{
public override void Execute()
{
public override void Execute()
{
var ids = UiDocument.Selection.GetElementIds();
List<ElementId> li = new List<ElementId>();
foreach (var id in ids)
{
var elem = Document.GetElement(id);
var param = elem.get_Parameter(BuiltInParameter.DOOR_NUMBER).AsString();
if (string.IsNullOrEmpty(param))
{
li.Add(elem.Id);
}
}
UiDocument.Selection.SetElementIds(li);
}
}
private void ReadExcel(string path)
{
FileInfo fi = new(path);
using ExcelPackage package = new(fi);
var worksheet = package.Workbook.Worksheets[1];
////获取worksheet的行数
//int rows = worksheet .Dimension.End.Row;
////获取worksheet的列数
//int cols = worksheet .Dimension.End.Column;
//worksheet.TrimLastEmptyRows();
private void ReadExcel(string path)
{
FileInfo fi = new(path);
using ExcelPackage package = new(fi);
var worksheet = package.Workbook.Worksheets[1];
////获取worksheet的行数
//int rows = worksheet .Dimension.End.Row;
////获取worksheet的列数
//int cols = worksheet .Dimension.End.Column;
//worksheet.TrimLastEmptyRows();
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;
try
{
var items = package.ToList<CodeItem>(1, configuration => configuration.SkipCastingErrors());
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;
try
{
var items = package.ToList<CodeItem>(1, configuration => configuration.SkipCastingErrors());
var elems = new FilteredElementCollector(Document)
.OfCategory(BuiltInCategory.OST_SecurityDevices)
.WhereElementIsNotElementType();
StringBuilder sb = new();
using var trans = new Transaction(Document, "读取Excel");
trans.Start();
var elems = new FilteredElementCollector(Document)
.OfCategory(BuiltInCategory.OST_SecurityDevices)
.WhereElementIsNotElementType();
StringBuilder sb = new();
using var trans = new Transaction(Document, "读取Excel");
trans.Start();
foreach (var elem in elems)
{
foreach (var item in items)
{
var param = elem.GetParameters("ID-100-编号").FirstOrDefault();
if (param?.HasValue != true)
{
sb.AppendLine(elem.Id.ToString());
}
var param1 = elem.get_Parameter(BuiltInParameter.DOOR_NUMBER);
if (param.AsString() == item.Origin)
{
param1.Set($"{item.Target}");
}
}
}
trans.Commit();
if (sb.Length > 0)
{
System.Windows.MessageBox.Show(sb.ToString());
}
//foreach (ParamterModel eamFacility in Items) { }
foreach (var elem in elems)
{
foreach (var item in items)
{
var param = elem.GetParameters("ID-100-编号").FirstOrDefault();
if (param?.HasValue != true)
{
sb.AppendLine(elem.Id.ToString());
}
var param1 = elem.get_Parameter(BuiltInParameter.DOOR_NUMBER);
if (param.AsString() == item.Origin)
{
param1.Set($"{item.Target}");
}
}
}
trans.Commit();
if (sb.Length > 0)
{
System.Windows.MessageBox.Show(sb.ToString());
}
//foreach (ParamterModel eamFacility in Items) { }
//var groups = Facilities .GroupBy(x => x.Story);
//foreach (var group in groups)
//{
// if (group .Key == null)
// {
// continue;
// }
// StoryCodeMappers .Add(new() { Story = group.Key, });
//}
//var groups = Facilities .GroupBy(x => x.Story);
//foreach (var group in groups)
//{
// if (group .Key == null)
// {
// continue;
// }
// StoryCodeMappers .Add(new() { Story = group.Key, });
//}
//IsMapper = false;
//IsComparison = false;
//Instances .ForEach(ins => ins.IsMapped = false);
}
catch (EPPlus.Core.Extensions.Exceptions.ExcelValidationException)
{
System.Windows.MessageBox.Show("列名不存在或不匹配或检查表头是否存在换行。");
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainOnAssemblyResolve;
}
}
//IsMapper = false;
//IsComparison = false;
//Instances .ForEach(ins => ins.IsMapped = false);
}
catch (EPPlus.Core.Extensions.Exceptions.ExcelValidationException)
{
System.Windows.MessageBox.Show("列名不存在或不匹配或检查表头是否存在换行。");
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainOnAssemblyResolve;
}
}
private static Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args)
{
if (!args.Name.Contains("ComponentModel.Annotations"))
{
return null;
}
private static Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args)
{
if (!args.Name.Contains("ComponentModel.Annotations"))
{
return null;
}
var assemblyFile = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"System.ComponentModel.Annotations.dll"
);
return File.Exists(assemblyFile) ? Assembly.LoadFrom(assemblyFile) : null;
}
var assemblyFile = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"System.ComponentModel.Annotations.dll"
);
return File.Exists(assemblyFile) ? Assembly.LoadFrom(assemblyFile) : null;
}
}

View File

@@ -1,13 +1,10 @@
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Xml.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.Creation;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Nice3point.Revit.Toolkit.External;

View File

@@ -12,6 +12,7 @@
<Platforms>AnyCPU;x64</Platforms>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
<RevitVersion>2018</RevitVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>$(DefineConstants);REVIT2018</DefineConstants>
@@ -26,17 +27,17 @@
<PackageReference Include="EleCho.WpfSuite" Version="0.9.1.2" />
<PackageReference Include="LiteDB" Version="5.0.21" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.135" />
<PackageReference Include="Nice3point.Revit.Api.Adwindows" Version="2018.*" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.UIFramework" Version="2018.*" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.RevitAPI" Version="2018.*" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.RevitAPIUI" Version="2018.*" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.UIFrameworkServices" Version="2020.2.60" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.Adwindows" Version="$(RevitVersion).*" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.UIFramework" Version="$(RevitVersion).*" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.RevitAPI" Version="$(RevitVersion).*" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.RevitAPIUI" Version="$(RevitVersion).*" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Api.UIFrameworkServices" Version="$(RevitVersion).*" PrivateAssets="All" />
<PackageReference Include="CommunityToolkit.Common" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.2" />
<PackageReference Include="EPPlus.Core.Extensions" Version="2.4.0" />
<PackageReference Include="JerryShaw.AduSkin" Version="1.1.1.11" />
<PackageReference Include="Nice3point.Revit.Toolkit" Version="2019.0.12" PrivateAssets="All" />
<PackageReference Include="Nice3point.Revit.Toolkit" Version="2019.*" PrivateAssets="All" />
<PackageReference Include="WPF-UI" Version="4.0.0-rc.2" />
</ItemGroup>
<Import Project="..\Sai.Toolkit.Revit\Sai.Toolkit.Revit.projitems" Label="Shared" />

View File

@@ -1,94 +0,0 @@
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.UI;
namespace RvAddinTest
{
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class SetDimensions : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
//程序UI界面
var uiapp = commandData.Application;
//获取元素(选择) 显示元素 视图(活动视图)管理(对象)
var uidoc = uiapp.ActiveUIDocument;
//程序
var app = uiapp.Application;
//获取位置和场地 视图(多个视图)管理 获取元素Revit 项目里的全部元素)
var doc = uidoc.Document;
//获取所有打开文档
var docset = uiapp.Application.Documents;
//当前视图
var view = doc.ActiveView;
try
{
var refers = uidoc.Selection.GetElementIds();
var toRotate = new List<IndependentTag>();
var toDelete = new List<ElementId>();
foreach (var item in refers)
{
var e = doc.GetElement(item) as IndependentTag;
var mep = doc.GetElement(e.TaggedElementId.HostElementId);
var loc = mep.Location as LocationCurve;
var c = loc.Curve.Length < 2;
if (c || Math.Abs((loc.Curve as Line).Direction.Z) > 0.2)
{
toDelete.Add(item);
continue;
}
if (loc.Curve is Line l)
{
var ra = l.Direction.AngleTo(XYZ.BasisX);
if (ra > Math.PI / 4 && ra < Math.PI / 4 * 3)
{
toRotate.Add(e);
}
}
}
using (var ts = new Transaction(doc, "旋转标注"))
{
ts.Start();
foreach (var item in toRotate)
{
item.TagOrientation = TagOrientation.Vertical;
}
doc.Delete(toDelete);
ts.Commit();
}
}
catch (Exception ex)
{
}
#region FilterExecute
//System.Collections.Generic.List<ElementId> col = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType()
// .Where(e => e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS)?.AsString() == "380/220V电源")
// .Select(e => e.Id).ToList();
//uidoc.Selection.SetElementIds(col);
//Reference refer = uidoc.Selection.PickObject(ObjectType.Element, "请选择XXX");
//var revitLink = uidoc.Document.GetElement(refer) as RevitLinkInstance;
//var linkDoc = revitLink.GetLinkDocument();
//var wallIds = new FilteredElementCollector(linkDoc).OfClass(typeof(Wall)).ToElementIds ();
//Debug.WriteLine(wallIds.Count);
//using (var ts=new Transaction(doc,"Copy"))
//{
// ts.Start();
// ElementTransformUtils.CopyElements(linkDoc, wallIds, doc, Transform.Identity, new CopyPasteOptions());
// ts.Commit();
//}
//foreach (Wall wall in walls)
//{
// Debug.WriteLine(wall.Id);
// Thread.Sleep(500);
//}
#endregion SelectExecute
return Result.Succeeded;
}
}
}

View File

@@ -1,20 +1,11 @@
using System;
using System.Net;
using System.Windows;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using CommunityToolkit.Mvvm.DependencyInjection;
using Nice3point.Revit.Toolkit.External;
using Sai.Toolkit.Revit.Assist;
using Sai.Toolkit.Revit.Helpers;
namespace RvAddinTest;
[Transaction(TransactionMode.Manual)]
@@ -204,19 +195,4 @@ public class TempCmd : ExternalCommand
}
}, "CMD");
}
public class ArrangeElement
{
public XYZ Translation { get; set; }
public int Index { get; set; }
public Element ElementToMove { get; set; }
/// <summary>
/// 与基准元素的间距及方向向量
/// </summary>
public XYZ HorizonDistanceVector { get; set; }
}
}

View File

@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# 17
# Visual Studio Version 17
VisualStudioVersion = 17.1.32421.90
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sai.RvKits", "Sai.RvKits\Sai.RvKits.csproj", "{AA64ED67-E47E-46B1-A6F6-999A26193E57}"
@@ -33,6 +33,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sai.RvKits Setup", "Sai.RvK
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp", "ConsoleApp\ConsoleApp.csproj", "{3F3C932B-851E-48D4-9D35-09DDBDD0F690}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WPFUIAPP", "WPFUIAPP\WPFUIAPP.csproj", "{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
All|Any CPU = All|Any CPU
@@ -207,6 +209,26 @@ Global
{3F3C932B-851E-48D4-9D35-09DDBDD0F690}.Release|Any CPU.Build.0 = Release|Any CPU
{3F3C932B-851E-48D4-9D35-09DDBDD0F690}.Release|x64.ActiveCfg = Release|Any CPU
{3F3C932B-851E-48D4-9D35-09DDBDD0F690}.Release|x64.Build.0 = Release|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.All|Any CPU.ActiveCfg = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.All|Any CPU.Build.0 = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.All|x64.ActiveCfg = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.All|x64.Build.0 = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Debug One|Any CPU.ActiveCfg = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Debug One|Any CPU.Build.0 = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Debug One|x64.ActiveCfg = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Debug One|x64.Build.0 = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Debug|x64.Build.0 = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.DefaultBuild|Any CPU.ActiveCfg = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.DefaultBuild|Any CPU.Build.0 = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.DefaultBuild|x64.ActiveCfg = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.DefaultBuild|x64.Build.0 = Debug|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Release|Any CPU.Build.0 = Release|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Release|x64.ActiveCfg = Release|Any CPU
{B0794664-92A5-44AC-AAD2-DB7C4A79A3A9}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -14,7 +14,6 @@ using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using Nice3point.Revit.Toolkit.External.Handlers;
using Nice3point.Revit.Toolkit.Utils;
using Sai.RvKits.Windows;
@@ -24,36 +23,10 @@ namespace Sai.RvKits.RvFamily;
public partial class ModelCheckViewModel : ObservableObject
{
private readonly ActionEventHandler showElementsSectionBox = new();
private readonly CorrectReferLevelExecutes correctReferLevelExecutes;
[ObservableProperty]
private bool useSectionBox;
[ObservableProperty]
private bool isCheckEqual;
[ObservableProperty]
private bool isCheckLength;
[ObservableProperty]
private bool isCheckLevel;
[ObservableProperty]
private bool isCheckName;
[ObservableProperty]
private bool isCheckProps;
[ObservableProperty]
private bool isCheckSlope;
[ObservableProperty]
private bool isCheckSymbolGeometry;
[ObservableProperty]
private int errorCount;
private readonly ActionEventHandler modifyModel = new();
private readonly ActionEventHandler showElementsSectionBox = new();
private readonly UIApplication uiapp;
public ModelCheckViewModel(UIApplication uiapp)
@@ -66,6 +39,15 @@ public partial class ModelCheckViewModel : ObservableObject
FindBasePoint();
}
private bool CanExport()
{
return Items.Any();
}
private static bool CanShowElement(object obj)
{
return obj is MessageModel { IsInstance: true };
}
[RelayCommand]
private /*async Task*/ void CheckModel(/*CancellationToken token*/)
{
@@ -357,45 +339,6 @@ public partial class ModelCheckViewModel : ObservableObject
ExportToExcelCommand.NotifyCanExecuteChanged();
}
private void FindBasePoint()
{
var basePoints = uiapp.ActiveUIDocument.Document.OfClass<BasePoint>().OfType<BasePoint>();
foreach (var item in basePoints)
{
//南北
var ns = Math.Round(
item.get_Parameter(BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM).AsDouble() * 0.3048,
4,
MidpointRounding.AwayFromZero
);
//东西
var ew = Math.Round(item.get_Parameter(BuiltInParameter.BASEPOINT_EASTWEST_PARAM).AsDouble() * 0.3048, 4, MidpointRounding.AwayFromZero);
//高程
var elev = Math.Round(
item.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM).AsDouble() * 0.3048,
4,
MidpointRounding.AwayFromZero
);
if (item.IsShared)//测量点
{
SharedBasePoint = $"南北:{ns}m东西{ew}m高程{elev}m";
continue;
}
if (item.Category.GetHashCode() == -2001271)//项目基点
{
//正北角度
var angle = item.get_Parameter(BuiltInParameter.BASEPOINT_ANGLETON_PARAM).AsValueString();
ProjectBasePoint = $"南北:{ns}m东西{ew}m高程{elev}m角度{angle}";
}
}
}
private bool CanExport()
{
return Items.Any();
}
[RelayCommand(CanExecute = nameof(CanExport))]
private void ExportToExcel()
{
@@ -488,6 +431,40 @@ public partial class ModelCheckViewModel : ObservableObject
}
}
private void FindBasePoint()
{
var basePoints = uiapp.ActiveUIDocument.Document.OfClass<BasePoint>().OfType<BasePoint>();
foreach (var item in basePoints)
{
//南北
var ns = Math.Round(
item.get_Parameter(BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM).AsDouble() * 0.3048,
4,
MidpointRounding.AwayFromZero
);
//东西
var ew = Math.Round(item.get_Parameter(BuiltInParameter.BASEPOINT_EASTWEST_PARAM).AsDouble() * 0.3048, 4, MidpointRounding.AwayFromZero);
//高程
var elev = Math.Round(
item.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM).AsDouble() * 0.3048,
4,
MidpointRounding.AwayFromZero
);
if (item.IsShared)//测量点
{
SharedBasePoint = $"南北:{ns}m东西{ew}m高程{elev}m";
continue;
}
if (item.Category.GetHashCode() == -2001271)//项目基点
{
//正北角度
var angle = item.get_Parameter(BuiltInParameter.BASEPOINT_ANGLETON_PARAM).AsValueString();
ProjectBasePoint = $"南北:{ns}m东西{ew}m高程{elev}m角度{angle}";
}
}
}
[RelayCommand]
private void ModifyModel()
{
@@ -576,10 +553,6 @@ public partial class ModelCheckViewModel : ObservableObject
SingletonChildWindowManager.ShowOrActivate<MessageWin, MessageViewModel>(uiapp.ActiveUIDocument, errorItems, "未解决错误");
});
}
private static bool CanShowElement(object obj)
{
return obj is MessageModel { IsInstance: true };
}
[RelayCommand(CanExecute = nameof(CanShowElement))]
private void ShowElement(object obj)
@@ -629,11 +602,39 @@ public partial class ModelCheckViewModel : ObservableObject
}
[ObservableProperty]
private ObservableCollection<MessageModel> items;
public partial int ErrorCount { get; set; }
[ObservableProperty]
public partial bool IsCheckEqual { get; set; }
[ObservableProperty]
public partial bool IsCheckLength { get; set; }
[ObservableProperty]
public partial bool IsCheckLevel { get; set; }
[ObservableProperty]
public partial bool IsCheckName { get; set; }
[ObservableProperty]
public partial bool IsCheckProps { get; set; }
[ObservableProperty]
public partial bool IsCheckSlope { get; set; }
[ObservableProperty]
public partial bool IsCheckSymbolGeometry { get; set; }
[ObservableProperty]
public partial ObservableCollection<MessageModel> Items { get; set; }
[ObservableProperty]
public partial int MyProperty { get; set; }
public string ProjectBasePoint { get; set; }
public string SharedBasePoint { get; set; }
[ObservableProperty]
public partial bool UseSectionBox { get; set; }
}
public enum ModelCheckType

View File

@@ -0,0 +1,17 @@
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Nice3point.Revit.Toolkit.External;
namespace Sai.RvKits.ModelManager;
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class SeparateModelCmd : ExternalCommand
{
public override void Execute()
{
//var win = new SeparateModelWin();
//win.Show();
SingletonChildWindowManager.ShowOrActivate<SeparateModelWin, SeparateModelViewModel>();
}
}

View File

@@ -0,0 +1,76 @@
using System.IO;
using System.Windows;
using Autodesk.Revit.DB;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Nice3point.Revit.Toolkit.External.Handlers;
using UIFrameworkServices;
namespace Sai.RvKits.ModelManager
{
public partial class SeparateModelViewModel : ObservableObject
{
private readonly ActionEventHandler separate = new();
[ObservableProperty]
private string fileName = "示例";
[ObservableProperty]
private string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
[RelayCommand]
private void Separate()
{
separate.Raise(
uiapp =>
{
var uidoc = uiapp.ActiveUIDocument;
var doc = uidoc.Document;
var list = uidoc.Selection.GetElementIds();
if (list.Count == 0)
{
MessageBox.Show("未选中元素", "提示");
return;
}
SpearateByIds(doc, list);
doc.Invoke(
ts =>
{
doc.Delete(list);
},
"删除元素");
});
}
private void SpearateByIds(Document doc, ICollection<ElementId> list)
{
var allOthers = doc.OfModelCollector()
.Excluding(list)
.ToElementIds();
var ids = doc.OfClass<ImportInstance>().ToElementIds();
var modelLineIds = doc.OfCollector().OfCategory(BuiltInCategory.OST_Lines).Select(e => e.Id).ToList();
var texts = doc.OfCollector().OfCategory(BuiltInCategory.OST_TextNotes).Select(e => e.Id).ToList();
doc.Invoke(
ts =>
{
doc.Delete(allOthers);
doc.Delete(ids);
doc.Delete(modelLineIds);
doc.Delete(texts);
},
"删除其他");
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
var filePath = Path.Combine(FolderPath, $"{FileName}.rvt");
SaveAsOptions options = new SaveAsOptions() { OverwriteExistingFile = true, PreviewViewId = doc.ActiveView.Id, Compact = true };
doc.SaveAs(filePath, options);
QuickAccessToolBarService.performMultipleUndoRedoOperations(true, 1);
}
}
}

View File

@@ -0,0 +1,37 @@
<ex:FluentWindowEx
x:Class="Sai.RvKits.ModelManager.SeparateModelWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ex="https://github.com/sherlockforrest/Wpf.Ui.Extend"
xmlns:local="clr-namespace:Sai.RvKits.ModelManager"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="拆分模型"
Width="300"
Height="300"
d:DataContext="{d:DesignInstance Type=local:SeparateModelViewModel}"
SizeToContent="Height"
Topmost="True"
mc:Ignorable="d">
<ex:FluentWindowEx.Resources>
<ResourceDictionary Source="pack://application:,,,/Sai.RvKits;component/WPFUI.xaml" />
</ex:FluentWindowEx.Resources>
<Grid>
<StackPanel Margin="5">
<ui:TextBox
Margin="5"
PlaceholderText="文件名"
Text="{Binding FileName, UpdateSourceTrigger=PropertyChanged}" />
<ui:TextBox
Margin="5"
PlaceholderText="保存路径"
Text="{Binding FolderPath, UpdateSourceTrigger=PropertyChanged}" />
<ui:Button
Margin="5"
HorizontalAlignment="Stretch"
Command="{Binding SeparateCommand}"
Content="拆分" />
</StackPanel>
</Grid>
</ex:FluentWindowEx>

View File

@@ -0,0 +1,14 @@
using Wpf.Ui.Extend.Controls;
namespace Sai.RvKits.ModelManager;
/// <summary>
/// SeparateModelWin.xaml 的交互逻辑
/// </summary>
public partial class SeparateModelWin : FluentWindowEx
{
public SeparateModelWin()
{
InitializeComponent();
}
}

View File

@@ -1,6 +1,5 @@
using System.Drawing;
using System.Drawing.Text;
using System.Windows;
using Autodesk.Revit.DB;
@@ -32,6 +31,56 @@ public partial class TemplateManagerViewModel : ObservableObject
fontFamilies = installedFonts.Families;
}
[RelayCommand]
private void CleanFontType()
{
handler.Raise(
uiapp =>
{
var doc = uiapp.ActiveUIDocument.Document;
var textTypes = doc.OfClass<TextNoteType>().ToList();
foreach (var type in textTypes)
{
{
if (type is TextNoteType textNoteType)
{
try
{
var font = textNoteType.get_Parameter(BuiltInParameter.TEXT_FONT).AsString();
var size = textNoteType.get_Parameter(BuiltInParameter.TEXT_SIZE).AsValueString().TrimEnd('m');
var dSize = Math.Round(Convert.ToDouble(size), 1, MidpointRounding.AwayFromZero);
if (dSize < 0.23)
{
return;
}
textNoteType.get_Parameter(BuiltInParameter.TEXT_SIZE).SetValueString(dSize.ToString());
var scale = textNoteType.get_Parameter(BuiltInParameter.TEXT_WIDTH_SCALE).AsValueString();
//var color = textNoteType.get_Parameter(BuiltInParameter.LINE_COLOR).AsInteger();
var name = $"{font}-{dSize}mm-{scale}";
var isExist = textTypes.FirstOrDefault(t => t.Name == name);
if (isExist != null)
{
var texts = doc.OfClass<TextNote>().Where(e => e.GetTypeId() == textNoteType.Id).ToList();
texts.ForEach(e => e.ChangeTypeId(isExist.Id));
doc.Regenerate();
doc.Delete(textNoteType.Id);
}
else
{
textNoteType.Name = name;
}
}
catch (Exception)
{
throw;
}
}
}
}
});
}
[RelayCommand]
private void ModifyFont()
{
handler.Raise(
@@ -44,9 +93,9 @@ public partial class TemplateManagerViewModel : ObservableObject
var col = doc.OfClass<Family>()
.Cast<Family>()
.Where(f => f.FamilyCategory.CategoryType == CategoryType.Annotation);
foreach(var family in col)
foreach (var family in col)
{
if(!family.IsEditable)
if (!family.IsEditable)
{
continue;
}
@@ -56,7 +105,7 @@ public partial class TemplateManagerViewModel : ObservableObject
ts =>
{
var textElements = familyEditing.OfClass<TextElement>().Cast<TextElement>();
foreach(var text in textElements)
foreach (var text in textElements)
{
var type = text.Symbol;
ElementType typeCopy;
@@ -64,7 +113,8 @@ public partial class TemplateManagerViewModel : ObservableObject
{
typeCopy = type.Duplicate(
$"{SelectFontFamily.Name} {FontSize} - {WidthScale}");
} catch(Autodesk.Revit.Exceptions.ArgumentException)
}
catch (Autodesk.Revit.Exceptions.ArgumentException)
{
}
type.get_Parameter(BuiltInParameter.TEXT_FONT)?.SetValueString(
@@ -76,14 +126,15 @@ public partial class TemplateManagerViewModel : ObservableObject
}
var textNotes = familyEditing.OfClass<TextNote>().Cast<TextNote>();
foreach(var text in textNotes)
foreach (var text in textNotes)
{
var type = text.Symbol;
try
{
var typeCopy = type.Duplicate(
$"{SelectFontFamily.Name} {FontSize} - {WidthScale}");
} catch(Autodesk.Revit.Exceptions.ArgumentException)
}
catch (Autodesk.Revit.Exceptions.ArgumentException)
{
}
type.get_Parameter(BuiltInParameter.TEXT_FONT)?.SetValueString(
@@ -101,7 +152,7 @@ public partial class TemplateManagerViewModel : ObservableObject
},
"载入族");
}
},"调整文字");
}, "调整文字");
});
}
}

View File

@@ -60,6 +60,26 @@ namespace Sai.RvKits.Properties {
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap adaptive_MEP_tag_16px {
get {
object obj = ResourceManager.GetObject("adaptive_MEP_tag_16px", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap adaptive_MEP_tag_32px {
get {
object obj = ResourceManager.GetObject("adaptive_MEP_tag_32px", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
@@ -220,16 +240,6 @@ namespace Sai.RvKits.Properties {
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap arrange_mep_16px1 {
get {
object obj = ResourceManager.GetObject("arrange_mep_16px1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
@@ -240,16 +250,6 @@ namespace Sai.RvKits.Properties {
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap arrange_mep_32px1 {
get {
object obj = ResourceManager.GetObject("arrange_mep_32px1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>

View File

@@ -499,10 +499,10 @@
<data name="add_insulation_32px" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\add_insulation_32px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrange_mep_16px1" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrange_mep_16px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
<data name="adaptive_MEP_tag_32px" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\adaptive_MEP_tag_32px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="arrange_mep_32px1" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\arrange_mep_32px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
<data name="adaptive_MEP_tag_16px" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\adaptive_MEP_tag_16px.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 447 B

View File

@@ -462,7 +462,7 @@ namespace Sai.RvKits.RvCommon
//{
// foreach (var curve in item)
// {
// previewIds.Add(DebugAssist.CreateTransientGeometries(doc, curve));
// previewIds.Add(DebugAssist.CreateTransientElements(doc, curve));
// }
//}
//var solid = GeometryCreationUtilities.CreateSweptGeometry(

View File

@@ -1,5 +1,4 @@
using System;
using System.Diagnostics;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Packaging;

View File

@@ -1,12 +1,11 @@
using System.Security.Cryptography;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Nice3point.Revit.Toolkit.External;
using Nice3point.Revit.Toolkit.Utils;
namespace Sai.RvKits.RvMEP;
@@ -77,6 +76,42 @@ public class CorrectMEPCurveSlopeCmd : ExternalCommand
}
}, "修正坡度");
}
private void CorrectSlope()
{
var ids = UiDocument.Selection.GetElementIds();
Document.Modify(
set => set.Transaction).Commit((doc, t) =>
{
foreach (var id in ids)
{
var elem = Document.GetElement(id);
if (elem is MEPCurve mep)
{
var loc = mep.GetCurve() as Line;
var x = Math.Round(loc.Direction.X);
var y = Math.Round(loc.Direction.Y);
var z = Math.Round(loc.Direction.Z);
//if (Math.Abs(x) < 10E-5)
//{
// x = 0;
//}
//if (Math.Abs(y) < 10E-5)
//{
// y = 0;
//}
//if (Math.Abs(z) < 10E-5)
//{
// z = 0;
//}
var dir = new XYZ(x, y, z);
var endPoint = loc.Origin + dir * loc.Length;
var li = Line.CreateBound(loc.Origin, endPoint);
var locx = mep.GetLocationCurve();
locx.Curve = li;
}
}
});
}
private void ModifyMEPCurve(MEPCurve mepCurve)
{
var loc = mepCurve.Location as LocationCurve;

View File

@@ -0,0 +1,57 @@
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Nice3point.Revit.Toolkit.External;
namespace Sai.RvKits.RvView;
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class AdaptiveMEPTagCmd : ExternalCommand
{
public override void Execute()
{
try
{
var tags = UiDocument.SelectObjects<IndependentTag>();
var toRotate = new List<IndependentTag>();
var toDelete = new List<ElementId>();
foreach (var tag in tags)
{
var mep = Document.GetElement(tag.TaggedElementId.HostElementId);
var loc = mep.Location as LocationCurve;
var c = loc.Curve.Length < 2;
if (c || Math.Abs((loc.Curve as Line).Direction.Z) > 0.2)
{
toDelete.Add(tag.Id);
continue;
}
if (loc.Curve is Line l)
{
var ra = l.Direction.AngleTo(XYZ.BasisX);
if (ra > Math.PI / 4 && ra < Math.PI / 4 * 3)
{
toRotate.Add(tag);
}
}
}
Document.Invoke(
ts =>
{
foreach (var item in toRotate)
{
item.TagOrientation = TagOrientation.Vertical;
}
Document.Delete(toDelete);
}, "旋转标注");
}
catch (Autodesk.Revit.Exceptions.OperationCanceledException)
{
}
catch (Exception)
{
}
}
}

View File

@@ -18,11 +18,17 @@
Spacing="5">
<ui:Button
x:Name="HideElements"
Margin="0,5"
Click="Btn_Click"
Content="隐藏对象"
Content="隐藏元素"
Icon="{ui:SymbolIcon SlideHide20,
False}" />
<ui:Button
x:Name="HideElementsAll"
Click="Btn_Click"
Content="隐藏所有"
Icon="{ui:SymbolIcon SlideHide24,
False}"
ToolTip="在所有视图中隐藏该元素" />
<!--<Button
x:Name="HideCategories"
Height="30"
@@ -39,7 +45,7 @@
<ui:Button
x:Name="PinElements"
Click="Btn_Click"
Content="锁定对象"
Content="锁定元素"
Icon="{ui:SymbolIcon LockClosed20,
False}" />
<ui:Button
@@ -63,7 +69,7 @@
<ui:Button
x:Name="IsolateElements"
Click="Btn_Click"
Content="隔离对象"
Content="隔离元素"
Icon="{ui:SymbolIcon SearchVisual20,
False}" />
<ui:Button

View File

@@ -3,7 +3,6 @@ using System.Windows.Controls;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Nice3point.Revit.Toolkit.External.Handlers;
@@ -36,188 +35,146 @@ public partial class ElementsControlDock : Page, IDockablePaneProvider
ElementClassFilter instanceFilter = new(typeof(FamilyInstance));
ElementClassFilter hostFilter = new(typeof(HostObject));
LogicalOrFilter orFilter = new(instanceFilter, hostFilter);
if (HideElements == btn)
ActionEventHandler.Raise(app =>
{
ActionEventHandler.Raise(app =>
{
var uidoc = app.ActiveUIDocument;
var doc = uidoc.Document;
var selectedIds = uidoc.Selection.GetElementIds();
doc.Invoke(_ => uidoc.Document.ActiveView.HideElements(selectedIds), "隐藏对象");
});
}
else if (IsolateElements == btn)
{
ActionEventHandler.Raise(app =>
{
var uidoc = app.ActiveUIDocument;
var doc = app.ActiveUIDocument.Document;
var selection = uidoc.Selection;
var selectedIds = selection.GetElementIds();
var collector = new FilteredElementCollector(doc, uidoc.ActiveView.Id)
.WherePasses(orFilter)
.Excluding(selectedIds)
.ToElementIds();
doc.Invoke(_ => uidoc.ActiveView.HideElements(collector), "隔离对象");
});
}
else if (RevealHiddenElements == btn)
{
ActionEventHandler.Raise(app =>
{
var doc = app.ActiveUIDocument.Document;
var uidoc = app.ActiveUIDocument;
var view = uidoc.Document.ActiveView;
if (doc.IsFamilyDocument)
var uidoc = app.ActiveUIDocument;
var doc = uidoc.Document;
//得到选择对象的ID
var selectedIds = uidoc.Selection.GetElementIds();
var view = uidoc.ActiveView;
doc.Invoke(
ts =>
{
ElementClassFilter formFilter = new(typeof(GenericForm));
ElementClassFilter combineFilter = new(typeof(GeomCombination));
orFilter = new(
[instanceFilter, formFilter, combineFilter]);
}
var hiddenElemsIds = new FilteredElementCollector(doc)
.WherePasses(orFilter)
.Where(e => e.IsHidden(view))
.Select(e => e.Id).ToList();
doc.Invoke(_ => view.UnhideElements(hiddenElemsIds), "显示隐藏");
});
}
else if (PinElements == btn)
{
ActionEventHandler.Raise(app =>
{
var uidoc = app.ActiveUIDocument;
var doc = app.ActiveUIDocument.Document;
var selectedIds = uidoc.Selection.GetElementIds();
doc.Invoke(_ =>
{
foreach (var eleId in selectedIds)
//隐藏元素
if (HideElements == btn)
{
var ele = doc.GetElement(eleId);
if (!ele.Pinned)
view.HideElements(selectedIds);
}
//所有视图隐藏元素
else if (HideElementsAll == btn)
{
var col = doc.OfClass<View>()
.WhereElementIsNotElementType()
.Cast<View>()
.Where(v => !v.IsTemplate);
foreach (var v in col)
{
ele.Pinned = true;
v.HideElements(uidoc.Selection.GetElementIds());
}
}
}, "锁定对象");
});
}
else if (PinCategories == btn)
{
ActionEventHandler.Raise(app =>
{
var uidoc = app.ActiveUIDocument;
var doc = app.ActiveUIDocument.Document;
var selectedIds = uidoc.Selection.GetElementIds();
var groups = selectedIds.GroupBy(id => doc.GetElement(id).Category.Id);
doc.Invoke(_ =>
{
foreach (var group in groups)
//隔离元素
else if (IsolateElements == btn)
{
new FilteredElementCollector(doc)
.OfCategoryId(group.Key)
.Where(elem => !elem.Pinned)
.ToList()
.ForEach(elem => elem.Pinned = true);
var collector = view.OfCollector()
.WherePasses(orFilter)
.Excluding(selectedIds)
.ToElementIds();
doc.Invoke(_ => view.HideElements(collector), $"{btn.Content}");
}
}, "锁定类别");
});
}
else if (HideCategories == btn)
{
ActionEventHandler.Raise(app =>
{
//RevitCommandId cmdId = RevitCommandId.LookupPostableCommandId(PostableCommand.HideCategory);
//app.PostCommand(cmdId);
var uidoc = app.ActiveUIDocument;
var doc = app.ActiveUIDocument.Document;
//得到选择对象的ID
var selectedIds = uidoc.Selection.GetElementIds();
var groups = selectedIds.GroupBy(id => doc.GetElement(id).Category.Id);
doc.Invoke(_ =>
{
foreach (var group in groups)
//显示隐藏
else if (RevealHiddenElements == btn)
{
var collector = new FilteredElementCollector(doc, uidoc.ActiveView.Id).OfCategoryId(group.Key).ToElementIds();
uidoc.ActiveView.HideElements(collector);
//相当于在VV菜单中关闭类别显示
//if (!UiDocument.ActiveView.GetCategoryHidden(category.Id))
//{
// UiDocument.Document.ActiveView.SetCategoryHidden(category.Id, true);
//}
}
}, "隐藏类别");
});
}
else if (IsolateCategories == btn)
{
ActionEventHandler.Raise(app =>
{
var uidoc = app.ActiveUIDocument;
var doc = app.ActiveUIDocument.Document;
//得到选择对象的ID
var selectedIds = uidoc.Selection.GetElementIds();
if (doc.IsFamilyDocument)
{
ElementClassFilter formFilter = new(typeof(GenericForm));
ElementClassFilter combineFilter = new(typeof(GeomCombination));
var collector = new FilteredElementCollector(doc, uidoc.ActiveView.Id)
.WherePasses(orFilter)
.ToElementIds();
doc.Invoke(_ =>
{
uidoc.ActiveView.HideElements(collector);
var groups = selectedIds.GroupBy(id => doc.GetElement(id).Category.Id);
foreach (var group in groups)
{
var collection = new FilteredElementCollector(doc, uidoc.ActiveView.Id).OfCategoryId(group.Key).ToElementIds();
uidoc.Document.ActiveView.UnhideElements(collection);
orFilter = new(
[instanceFilter, formFilter, combineFilter]);
}
var hiddenElemsIds = doc.OfCollector()
.WherePasses(orFilter)
.Where(e => e.IsHidden(view))
.Select(e => e.Id).ToList();
doc.Invoke(_ => view.UnhideElements(hiddenElemsIds), $"{btn.Content}");
}
}, "隔离类别");
});
}
else if (UnpinAllElements == btn)
{
ActionEventHandler.Raise(app =>
{
var doc = app.ActiveUIDocument.Document;
doc.Invoke(_ =>
{
new FilteredElementCollector(doc)
.WherePasses(orFilter)
.Where(elem => elem.Pinned)
.ToList()
.ForEach(elem => elem.Pinned = false);
}, "解锁全部");
});
}
else if (UnpinCategories == btn)
{
ActionEventHandler.Raise(app =>
{
var uidoc = app.ActiveUIDocument;
var doc = app.ActiveUIDocument.Document;
//得到选择对象的ID
var selectedIds = uidoc.Selection.GetElementIds();
doc.Invoke(_ =>
{
var groups = selectedIds.GroupBy(id => doc.GetElement(id).Category.Id);
foreach (var group in groups)
//锁定元素
else if (PinElements == btn)
{
new FilteredElementCollector(doc)
.OfCategoryId(group.Key)
.Where(elem => elem.Pinned)
.ToList()
.ForEach(e => e.Pinned = false);
foreach (var eleId in selectedIds)
{
var ele = doc.GetElement(eleId);
if (!ele.Pinned)
{
ele.Pinned = true;
}
}
}
}, "解锁类别");
});
}
//锁定类别
else if (PinCategories == btn)
{
var groups = selectedIds.GroupBy(id => doc.GetElement(id).Category.Id);
doc.Invoke(_ =>
{
foreach (var group in groups)
{
doc.OfCollector()
.OfCategoryId(group.Key)
.Where(elem => !elem.Pinned)
.ToList()
.ForEach(elem => elem.Pinned = true);
}
}, $"{btn.Content}");
}
//隐藏类别
else if (HideCategories == btn)
{
var groups = selectedIds.GroupBy(id => doc.GetElement(id).Category.Id);
doc.Invoke(_ =>
{
foreach (var group in groups)
{
var collector = view.OfCollector().OfCategoryId(group.Key).ToElementIds();
view.HideElements(collector);
//相当于在VV菜单中关闭类别显示
//if (!UiDocument.ActiveView.GetCategoryHidden(category.Id))
//{
// UiDocument.Document.ActiveView.SetCategoryHidden(category.Id, true);
//}
}
}, $"{btn.Content}");
}
//隔离类别
else if (IsolateCategories == btn)
{
var collector = view.OfCollector()
.WherePasses(orFilter)
.ToElementIds();
view.HideElements(collector);
var groups = selectedIds.GroupBy(id => doc.GetElement(id).Category.Id);
foreach (var group in groups)
{
var collection = view.OfCollector().OfCategoryId(group.Key).ToElementIds();
view.UnhideElements(collection);
}
}
//解锁全部
else if (UnpinAllElements == btn)
{
doc.OfCollector()
.WherePasses(orFilter)
.Where(elem => elem.Pinned)
.ToList()
.ForEach(elem => elem.Pinned = false);
}
//解锁类别
else if (UnpinCategories == btn)
{
var groups = selectedIds.GroupBy(id => doc.GetElement(id).Category.Id);
foreach (var group in groups)
{
doc.OfCollector()
.OfCategoryId(group.Key)
.Where(elem => elem.Pinned)
.ToList()
.ForEach(e => e.Pinned = false);
}
}
},
$"{btn.Content}");
});
}
}

View File

@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LangVersion>13.0</LangVersion>
<LangVersion>preview</LangVersion>
<Configurations>Debug;Release</Configurations>
<AccelerateBuildsInVisualStudio>True</AccelerateBuildsInVisualStudio>
<!-- 添加默认的五个命名空间 -->
@@ -80,15 +80,15 @@
<Reference Include="UIFrameworkServices" HintPath="..\libs\$(RevitVersion)\UIFrameworkServices.dll" Private="False" />-->
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Common" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Common" Version="8.4.0" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.4.0" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="EPPlus.Core.Extensions" Version="2.4.0" />
<PackageReference Include="ACadSharp" Version="1.0.3" />
<PackageReference Include="ACadSharp" Version="1.0.8" />
<PackageReference Include="FuzzySharp" Version="2.0.2" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.70" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.72" />
<!--TreatAsUsed="true"标记为已使用-->
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.122" TreatAsUsed="True"/>
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.135" TreatAsUsed="True" />
<PackageReference Include="randomColorSharped.NetStandard" Version="1.0.2" />
</ItemGroup>
<!-- <ItemGroup Condition="$(DefineConstants.Contains('WINFORMS'))"> -->
@@ -106,6 +106,7 @@
<PackageReference Include="Autodesk.Revit.SDK" Version="2025.*" Condition=" '$(RevitVersion)' == '2025' " PrivateAssets="All" />-->
<PackageReference Include="Nice3point.Revit.Toolkit" Version="2019.*" Condition=" '$(RevitVersion)' == '2018' " />
<PackageReference Include="Nice3point.Revit.Toolkit" Version="2020.*" Condition=" '$(RevitVersion)' == '2020' " />
<PackageReference Include="ValueConverters" Version="3.1.22" />
<!--<PackageReference Include="Nice3point.Revit.Toolkit" Version="2025.*" Condition=" '$(RevitVersion)' == '2025' " />-->
</ItemGroup>
@@ -142,6 +143,11 @@
</Content>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="Resources\adaptive_MEP_tag_16px.png" />
<EmbeddedResource Remove="Resources\adaptive_MEP_tag_32px.png" />
</ItemGroup>
<ItemGroup>
<None Remove="Resources\add_insulation_16px.png" />
<None Remove="Resources\add_insulation_32px.png" />
@@ -166,6 +172,9 @@
</ItemGroup>
<ItemGroup>
<Compile Update="ModelManager\SeparateModelWin.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>

View File

@@ -1,7 +1,5 @@
using System;
using System.Windows;
using System.Windows;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Windows;
@@ -10,8 +8,6 @@ using Nice3point.Revit.Toolkit.External.Handlers;
using Sai.RvKits.Properties;
using Sai.RvKits.RvView;
using adWin = Autodesk.Windows;
namespace Sai.RvKits.UIRibbon;
public class DrawingViewApp
@@ -46,6 +42,12 @@ public class DrawingViewApp
Resources.two_lines_16px,
"选择要标注的两条平行的几何模型边缘线进行标注。"
);
var adaptiveMEPTag = UIAssist.NewPushButtonData<AdaptiveMEPTagCmd>(
"自适应标记",
Resources.adaptive_MEP_tag_32px,
Resources.adaptive_MEP_tag_16px,
"删除距离过密的标记及管上标记方向调整"
);
var visibilityControl = UIAssist.NewPushButtonData<VisibilityControlCmd>(
"可见性",
@@ -98,7 +100,7 @@ public class DrawingViewApp
"元素菜单控制"
);
ribbonPanel.AddStackedItems(dim2Line, autoAlignTags, arrangeTags);
ribbonPanel.AddSplitButton("标记工具", dim2Line, autoAlignTags, arrangeTags, adaptiveMEPTag);
ribbonPanel.AddStackedItems(visibilityControl, sectionBox, filter);
//ribbonPanel.AddSplitButton(splitBtn1, dim2Line, autoAlignTags, arrangeTags);

View File

@@ -24,7 +24,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Behaviors\CloseByPropertyBehavior.cs" />
<Compile Include="$(MSBuildThisFileDirectory)BindingHelper.cs" />
<Compile Include="$(MSBuildThisFileDirectory)BindingProxy.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Converters\BoolInverterConverter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Converters\InvertBooleanConverter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Converters\ComparisonConverter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Converters\EnumDescriptionConverter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Converters\EnumSourceAndConverter.cs" />

View File

@@ -138,6 +138,10 @@ public static class CollectorAssist
&& e is not Panel
&& e is not Mullion
&& e is not RevitLinkInstance)).Select(e => e.Id).ToList();
if (li.Count == 0)
{
return new FilteredElementCollector(doc);
}
return new FilteredElementCollector(doc, li);
}

View File

@@ -1,9 +1,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics;
using System.Reflection;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
namespace Sai.Toolkit.Revit.Assist;
@@ -29,7 +27,7 @@ public static class DebugAssist
/// <param name="doc"></param>
/// <param name="geoms"></param>
/// <returns></returns>
public static ElementId CreateTransientGeometries(this Document doc, params GeometryObject[] geoms)
public static ElementId CreateTransientElements(this Document doc, params GeometryObject[] geoms)
{
var list = new List<GeometryObject>(geoms);
var method = GenerateTransientDisplayMethod();

View File

@@ -65,9 +65,9 @@ public static class ElementAssist
/// <summary>
/// 获取标高
/// </summary>
/// <param name="model"></param>
/// <param name="element"></param>
/// <returns></returns>
public static ElementId GetLevelId(this Element model)
public static ElementId GetLevelId(this Element element)
{
// 定义需要检查的参数列表
var parametersToCheck = new BuiltInParameter[]
@@ -84,7 +84,7 @@ public static class ElementAssist
// 依次检查每个参数
foreach (var param in parametersToCheck)
{
var baseLevelId = model.get_Parameter(param)?.AsElementId();
var baseLevelId = element.get_Parameter(param)?.AsElementId();
if (baseLevelId != ElementId.InvalidElementId && baseLevelId != null)
{
return baseLevelId;
@@ -92,7 +92,7 @@ public static class ElementAssist
}
//最后检查楼板或族基准标高
return model.LevelId;
return element.LevelId;
}
/// <summary>
/// 转换类型

View File

@@ -82,7 +82,9 @@ public class ElementInLinkOrCurrentDocument : ISelectionFilter
&& e is not Panel;
}
}
/// <summary>
/// dwg块选择过滤
/// </summary>
public class DwgBlockSelection : ISelectionFilter
{
private Element e;

View File

@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection;
using Autodesk.Revit.UI;
@@ -37,8 +34,26 @@ namespace Sai.Toolkit.Revit.Helpers
}
dictionary.Add(id, shortcutItem);
List<UIFrameworkServices.ShortcutItem> list = dictionary.Select((KeyValuePair<string, UIFrameworkServices.ShortcutItem> e) => e.Value).ToList<UIFrameworkServices.ShortcutItem>();
this.SaveShortcuts(list);
this.ArmCommands();
/* 项目“Sai.RvKits (net481)”的未合并的更改
在此之前:
this.SaveShortcuts(list);
this.ArmCommands();
在此之后:
SaveShortcuts(list);
this.ArmCommands();
*/
KeyboardShortcutService.SaveShortcuts(list);
/* 项目“Sai.RvKits (net481)”的未合并的更改
在此之前:
this.ArmCommands();
return true;
在此之后:
ArmCommands();
return true;
*/
KeyboardShortcutService.ArmCommands();
return true;
}
return false;
@@ -71,8 +86,26 @@ namespace Sai.Toolkit.Revit.Helpers
}
dictionary.Add(item.Key, shortcutItem);
List<UIFrameworkServices.ShortcutItem> list = dictionary.Select((KeyValuePair<string, UIFrameworkServices.ShortcutItem> e) => e.Value).ToList<UIFrameworkServices.ShortcutItem>();
this.SaveShortcuts(list);
this.ArmCommands();
/* 项目“Sai.RvKits (net481)”的未合并的更改
在此之前:
this.SaveShortcuts(list);
this.ArmCommands();
在此之后:
SaveShortcuts(list);
this.ArmCommands();
*/
KeyboardShortcutService.SaveShortcuts(list);
/* 项目“Sai.RvKits (net481)”的未合并的更改
在此之前:
this.ArmCommands();
return true;
在此之后:
ArmCommands();
return true;
*/
KeyboardShortcutService.ArmCommands();
return true;
}
}
@@ -155,8 +188,26 @@ namespace Sai.Toolkit.Revit.Helpers
{
dictionary.Remove(id);
List<UIFrameworkServices.ShortcutItem> list = dictionary.Select((KeyValuePair<string, UIFrameworkServices.ShortcutItem> e) => e.Value).ToList<UIFrameworkServices.ShortcutItem>();
this.SaveShortcuts(list);
this.ArmCommands();
/* 项目“Sai.RvKits (net481)”的未合并的更改
在此之前:
this.SaveShortcuts(list);
this.ArmCommands();
在此之后:
SaveShortcuts(list);
this.ArmCommands();
*/
KeyboardShortcutService.SaveShortcuts(list);
/* 项目“Sai.RvKits (net481)”的未合并的更改
在此之前:
this.ArmCommands();
return true;
在此之后:
ArmCommands();
return true;
*/
KeyboardShortcutService.ArmCommands();
return true;
}
return false;
@@ -214,7 +265,7 @@ namespace Sai.Toolkit.Revit.Helpers
/// <summary>
/// 加载命令
/// </summary>
public void LoadCommands()
public static void LoadCommands()
{
ShortcutsHelper.LoadCommands();
}
@@ -228,7 +279,7 @@ namespace Sai.Toolkit.Revit.Helpers
/// <summary>
/// 应用更改
/// </summary>
private void ArmCommands()
private static void ArmCommands()
{
ShortcutsHelper.ArmCommands();
}
@@ -244,7 +295,7 @@ namespace Sai.Toolkit.Revit.Helpers
/// 保存ShortcutItems
/// </summary>
/// <param name="shortcutList"></param>
private void SaveShortcuts(ICollection<UIFrameworkServices.ShortcutItem> shortcutList)
private static void SaveShortcuts(ICollection<UIFrameworkServices.ShortcutItem> shortcutList)
{
ShortcutsHelper.SaveShortcuts(shortcutList);
}

File diff suppressed because it is too large Load Diff

6
WPFUIAPP/App.config Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

19
WPFUIAPP/App.xaml Normal file
View File

@@ -0,0 +1,19 @@
<Application
x:Class="WPFUIAPP.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFUIAPP"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vio="http://schemas.lepo.co/wpfui/2022/xaml/violeta"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ui:ThemesDictionary Theme="Dark" />
<ui:ControlsDictionary />
<vio:ThemesDictionary Theme="Dark" />
<vio:ControlsDictionary />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

26
WPFUIAPP/App.xaml.cs Normal file
View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Wpf.Ui.Violeta.Controls;
namespace WPFUIAPP
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
public App()
{
Splash.ShowAsync("pack://application:,,,/Wpf.Ui.Test;component/wpfui.png");
InitializeComponent();
}
}
}

131
WPFUIAPP/MainWindow.xaml Normal file
View File

@@ -0,0 +1,131 @@
<ui:FluentWindow
x:Class="WPFUIAPP.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPFUIAPP"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vio="http://schemas.lepo.co/wpfui/2022/xaml/violeta"
Title="MainWindow"
Width="800"
Height="450"
ui:Design.Background="#252525"
ui:Design.Foreground="#252525"
mc:Ignorable="d">
<Grid>
<StackPanel>
<ui:TitleBar />
<ui:Button Click="Button_Click" Content="Toast" />
<ui:Button Content="Show Flyout">
<ui:FlyoutService.Flyout>
<ui:Flyout Placement="Bottom">
<StackPanel>
<TextBlock HorizontalAlignment="Left" Text="Show the flyout message here" />
<Button Command="{Binding GotItCommand}" Content="Got it" />
</StackPanel>
</ui:Flyout>
</ui:FlyoutService.Flyout>
</ui:Button>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<vio:ToggleButtonGroup x:Key="ToggleButtonGroup" />
</StackPanel.Resources>
<ToggleButton
vio:ToggleButtonGroup.Group="{DynamicResource ToggleButtonGroup}"
Content="1st"
IsChecked="True" />
<ToggleButton vio:ToggleButtonGroup.Group="{DynamicResource ToggleButtonGroup}" Content="2nd" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<vio:RadioButtonGroup x:Key="RadioButtonGroup" />
</StackPanel.Resources>
<RadioButton
vio:RadioButtonGroup.Group="{DynamicResource RadioButtonGroup}"
Content="1st"
IsChecked="True" />
<Grid>
<RadioButton
Margin="8,0,0,0"
vio:RadioButtonGroup.Group="{DynamicResource RadioButtonGroup}"
Content="2nd" />
</Grid>
</StackPanel>
<ui:TreeListView ItemsSource="{Binding StaffList}">
<ui:TreeListView.DataContext>
<local:ViewModel />
</ui:TreeListView.DataContext>
<ui:TreeListView.Columns>
<GridViewColumnCollection>
<ui:GridViewColumn Width="400" Header="Name">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:TreeRowExpander Content="{Binding Name}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
<ui:GridViewColumn
Width="80"
DisplayMemberBinding="{Binding Age}"
Header="Age" />
<ui:GridViewColumn
Width="80"
DisplayMemberBinding="{Binding Sex}"
Header="Sex" />
<ui:GridViewColumn
Width="100"
DisplayMemberBinding="{Binding Duty}"
Header="Duty" />
<ui:GridViewColumn Width="250" Header="IsChecked">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:ToggleSwitch IsChecked="{Binding IsChecked}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
</GridViewColumnCollection>
</ui:TreeListView.Columns>
<ui:TreeListView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding StaffList}" />
</ui:TreeListView.ItemTemplate>
</ui:TreeListView>
<Button Click="MsgSyncClick" Content="MessageBox" />
<Button Click="MsgAsyncClick" Content="MessageBoxAsync" />
<Button Click="PendingBoxClick" Content="PendingBox" />
<Button Click="ContentDialogClick" Content="ContentDialog" />
<Button Click="NewContentDialogClick" Content="NewContentDialog" />
<ui:TreeModelListView Model="{Binding TreeTestModel}">
<ui:TreeModelListView.DataContext>
<local:ViewModel2 />
</ui:TreeModelListView.DataContext>
<ui:GridView>
<ui:GridView.Columns>
<ui:GridViewColumn Width="400" Header="Column1">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:TreeModelRowExpander Content="{Binding Column1}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
<ui:GridViewColumn
Width="250"
DisplayMemberBinding="{Binding Column2, Mode=TwoWay}"
Header="Column2" />
<ui:GridViewColumn
Width="250"
DisplayMemberBinding="{Binding Column3, Mode=TwoWay}"
Header="Column3" />
<ui:GridViewColumn Width="250" Header="IsChecked">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:ToggleSwitch IsChecked="{Binding IsChecked}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
</ui:GridView.Columns>
</ui:GridView>
</ui:TreeModelListView>
</StackPanel>
</Grid>
</ui:FluentWindow>

View File

@@ -0,0 +1,89 @@
using System.Threading;
using System.Windows;
using Wpf.Ui.Controls;
using Wpf.Ui.Violeta.Controls;
using MessageBox = Wpf.Ui.Violeta.Controls.MessageBox;
namespace WPFUIAPP
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow
{
Wpf.Ui.Controls.ContentDialog dialog;
Wpf.Ui.Violeta.Controls.ContentDialog newdialog;
public MainWindow()
{
InitializeComponent();
dialog = new()
{
Title = "My sample dialog",
Content = "Content of the dialog",
CloseButtonText = "Close button",
PrimaryButtonText = "Primary button",
SecondaryButtonText = "Secondary button",
// Setting the dialog container
DialogHost = ContentDialogHostService.ContentPresenterForDialogs
};
newdialog = new()
{
Title = "My sample dialog",
Content = "Content of the dialog",
CloseButtonText = "Close button",
PrimaryButtonText = "Primary button",
SecondaryButtonText = "Secondary button",
DefaultButton = Wpf.Ui.Violeta.Controls.ContentDialogButton.Primary,
};
Splash.CloseOnLoaded(this, minimumMilliseconds: 1800);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Toast.Information("I am information message");
Toast.Error("I am error message");
//Toast.Success("I am success message");
//Toast.Warning("I am warning message");
//Toast.Show(owner: null, "I am any message", new ToastConfig());
}
private void MsgSyncClick(object sender, RoutedEventArgs e)
{
_ = MessageBox.Information("This is a information message");
_ = MessageBox.Warning("This is a warning message");
_ = MessageBox.Error("This is a error message");
var result = MessageBox.Question("This is a question and do you want to click OK?");
}
private async void MsgAsyncClick(object sender, RoutedEventArgs e)
{
// Async methods
_ = await MessageBox.InformationAsync("This is a information message");
_ = await MessageBox.WarningAsync("This is a warning message");
_ = await MessageBox.ErrorAsync("This is a error message");
var result = await MessageBox.QuestionAsync("This is a question and do you want to click OK?");
}
private void PendingBoxClick(object sender, RoutedEventArgs e)
{
// Default style.
using IPendingHandler pending = PendingBox.Show();
// Show with title and cancel button.
//using IPendingHandler pending = PendingBox.Show("Doing something", "I'm a title", isShowCancel: true);
}
private async void ContentDialogClick(object sender, RoutedEventArgs e)
{
await dialog.ShowAsync(CancellationToken.None);
}
private async void NewContentDialogClick(object sender, RoutedEventArgs e)
{
_ = await dialog.ShowAsync();
}
}
}

View File

@@ -0,0 +1,52 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("WPFUIAPP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WPFUIAPP")]
[assembly: AssemblyCopyright("Copyright © 2025")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请设置
//.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture>
//在 <PropertyGroup> 中。例如,如果你使用的是美国英语。
//使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消
//对以下 NeutralResourceLanguage 特性的注释。 更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(未在页面中找到资源时使用,
//或应用程序资源字典中找到时使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(未在页面中找到资源时使用,
//、应用程序或任何主题专用资源字典中找到时使用)
)]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WPFUIAPP.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WPFUIAPP.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

30
WPFUIAPP/Properties/Settings.Designer.cs generated Normal file
View File

@@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WPFUIAPP.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

160
WPFUIAPP/ViewModel.cs Normal file
View File

@@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
namespace WPFUIAPP
{
public partial class ViewModel : ObservableObject
{
[ObservableProperty]
private ObservableCollection<Staff> staffList = [];
public ViewModel()
{
InitNode1Value();
}
public void InitNode1Value()
{
Staff staff = new Staff()
{
Name = "Alice",
Age = 30,
Sex = "Male",
Duty = "Manager",
IsExpanded = true
};
Staff staff2 = new Staff()
{
Name = "Alice1",
Age = 21,
Sex = "Male",
Duty = "Normal",
IsExpanded = true
};
Staff staff3 = new Staff()
{
Name = "Alice11",
Age = 21,
Sex = "Male",
Duty = "Normal"
};
staff2.StaffList.Add(staff3);
staff3 = new Staff()
{
Name = "Alice22",
Age = 21,
Sex = "Female",
Duty = "Normal"
};
staff2.StaffList.Add(staff3);
staff.StaffList.Add(staff2);
staff2 = new Staff()
{
Name = "Alice2",
Age = 22,
Sex = "Female",
Duty = "Normal"
};
staff.StaffList.Add(staff2);
staff2 = new Staff()
{
Name = "Alice3",
Age = 23,
Sex = "Female",
Duty = "Normal"
};
staff.StaffList.Add(staff2);
StaffList.Add(staff);
staff = new Staff()
{
Name = "Bob",
Age = 31,
Sex = "Male",
Duty = "CEO"
};
staff2 = new Staff()
{
Name = "Bob1",
Age = 24,
Sex = "Female",
Duty = "Normal"
};
staff.StaffList.Add(staff2);
staff2 = new Staff()
{
Name = "Bob2",
Age = 25,
Sex = "Female",
Duty = "Normal"
};
staff.StaffList.Add(staff2);
staff2 = new Staff()
{
Name = "Bob3",
Age = 26,
Sex = "Male",
Duty = "Normal"
};
staff.StaffList.Add(staff2);
StaffList.Add(staff);
staff = new Staff()
{
Name = "Cyber",
Age = 32,
Sex = "Female",
Duty = "Leader"
};
staff2 = new Staff()
{
Name = "Cyber1",
Age = 27,
Sex = "Female",
Duty = "Normal"
};
staff.StaffList.Add(staff2);
staff2 = new Staff()
{
Name = "Cyber2",
Age = 28,
Sex = "Female",
Duty = "Normal"
};
staff.StaffList.Add(staff2);
StaffList.Add(staff);
}
}
public partial class Staff : ObservableObject
{
[ObservableProperty]
private string? name = null;
[ObservableProperty]
private int age;
[ObservableProperty]
private string? sex = null;
[ObservableProperty]
private string? duty = null;
[ObservableProperty]
private bool isChecked = true;
[ObservableProperty]
private bool isSelected = false;
[ObservableProperty]
private bool isExpanded = false;
[ObservableProperty]
private ObservableCollection<Staff> staffList = [];
}
}

71
WPFUIAPP/ViewModel2.cs Normal file
View File

@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using Wpf.Ui.Controls;
namespace WPFUIAPP;
public partial class ViewModel2 : ObservableObject
{
[ObservableProperty]
private TreeModelCollection<TreeTestModel> treeTestModel = CreateTestModel();
public static TreeModelCollection<TreeTestModel> CreateTestModel()
{
return new TreeModelCollection<TreeTestModel>()
{
Children = new(
[
new()
{
Column1 = "Test 1",
Column2 = "Test 1",
Column3 = "Test 1",
Children = new(
[
new()
{
Column1 = "Test 1.1",
Column2 = "Test 1.1",
Column3 = "Test 1.1",
Children = new(
[
new()
{
Column1 = "Test 1.2",
Column2 = "Test 1.2",
Column3 = "Test 1.2",
},
]),
},
]),
},
new()
{
Column1 = "Test 2",
Column2 = "Test 2",
Column3 = "Test 2",
}
]),
};
}
}
[ObservableObject]
public partial class TreeTestModel : TreeModelObject<TreeTestModel>
{
[ObservableProperty]
private string? column1;
[ObservableProperty]
private string? column2;
[ObservableProperty]
private string? column3;
[ObservableProperty]
private bool isChecked = false;
}

18
WPFUIAPP/WPFUIAPP.csproj Normal file
View File

@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<OutputType>WinExe</OutputType>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<UseWPF>true</UseWPF>
<Nullable>enable</Nullable>
<LangVersion>13.0</LangVersion>
<ImportWindowsDesktopTargets>true</ImportWindowsDesktopTargets>
<Configurations>All;Debug One;Debug;DefaultBuild;Release</Configurations>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.28" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
</ItemGroup>
</Project>

View File

@@ -15,7 +15,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="System.Runtime" Version="4.3.1" />
<PackageReference Include="WPF-UI" Version="4.0.0-rc.2" />
<PackageReference Include="WPF-UI" Version="4.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">

View File

@@ -3,7 +3,9 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Windows.Markup;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
@@ -13,6 +15,7 @@ using Sai.RvKits;
using Wpf.Ui;
using Wpf.Ui.Controls;
using Wpf.Ui.Extend.Controls;
using Wpf.Ui.Violeta.Controls;
namespace WpfApp
{
@@ -28,15 +31,20 @@ namespace WpfApp
[RelayCommand]
private void ButtonClick()
{
snackbarService = new SnackbarService();
snackbarService.SetSnackbarPresenter(SnackbarPresenter);
snackbarService.Show(
"消息",
"Test",
snackbarAppearance,
new SymbolIcon(SymbolRegular.Fluent24),
TimeSpan.FromSeconds(snackbarTimeout)
);
//snackbarService = new SnackbarService();
//snackbarService.SetSnackbarPresenter(SnackbarPresenter);
//snackbarService.Show(
// "消息",
// "Test",
// snackbarAppearance,
// new SymbolIcon(SymbolRegular.Fluent24),
// TimeSpan.FromSeconds(snackbarTimeout)
//);
Toast.Information("I am information message");
Toast.Error("I am error message");
Toast.Success("I am success message");
Toast.Warning("I am warning message");
Toast.Show(owner: null!, "I am any message", new ToastConfig());
}
[RelayCommand]
@@ -176,6 +184,7 @@ namespace WpfApp
public List<Student> Students { get; set; } = [];
}
class Student
{
public int ID { get; set; }

View File

@@ -167,6 +167,7 @@
MinHeight="30"
Padding="5"
ItemsSource="{Binding Items}" />-->
</ex:AutoGrid>
<ui:SnackbarPresenter
x:Name="SnackbarPresenter"

View File

@@ -12,10 +12,10 @@
<None Remove="Fonts\Segoe Fluent Icons.ttf" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Common" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.HighPerformance" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.2" />
<PackageReference Include="CommunityToolkit.Common" Version="8.4.0" />
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.4.0" />
<PackageReference Include="CommunityToolkit.HighPerformance" Version="8.4.0" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.135" />
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />