using Autodesk.AutoCAD.Windows.Data;
using System.ComponentModel;
using AcAp = Autodesk.AutoCAD.ApplicationServices.Application;
namespace WpfUiBindingSample
{
class AcadStylesControlViewModel : INotifyPropertyChanged
{
// INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged
?.Invoke(this,
new PropertyChangedEventArgs
(propertyName
)); }
// private fields
ICustomTypeDescriptor layer, textstyle, dimstyle, tablestyle, mleaderstyle;
// constructor (initialization of current style properties)
public AcadStylesControlViewModel()
{
Initialize(nameof(Clayer), Layers);
Initialize(nameof(Textstyle), TextStyles);
Initialize(nameof(Dimstyle), DimensionStyles);
Initialize(nameof(Tablestyle), TableStyles);
Initialize(nameof(MLeaderstyle), MleaderStyles);
}
// collection properties bound to AutoCAD via UIBindings
public DataItemCollection Layers => AcAp.UIBindings.Collections.Layers;
public DataItemCollection TextStyles => AcAp.UIBindings.Collections.TextStyles;
public DataItemCollection DimensionStyles => AcAp.UIBindings.Collections.DimensionStyles;
public DataItemCollection TableStyles => AcAp.UIBindings.Collections.TableStyles;
public DataItemCollection MleaderStyles => AcAp.UIBindings.Collections.MleaderStyles;
// current setting properties (same names as Database properties)
public ICustomTypeDescriptor Clayer
{
get { return layer; }
set { SetCurrentValue(nameof(Clayer), ref layer, value); }
}
public ICustomTypeDescriptor Textstyle
{
get { return textstyle; }
set { SetCurrentValue(nameof(Textstyle), ref textstyle, value); }
}
public ICustomTypeDescriptor Dimstyle
{
get { return dimstyle; }
set { SetCurrentValue(nameof(Dimstyle), ref dimstyle, value); }
}
public ICustomTypeDescriptor Tablestyle
{
get { return tablestyle; }
set { SetCurrentValue(nameof(Tablestyle), ref tablestyle, value); }
}
public ICustomTypeDescriptor MLeaderstyle
{
get { return mleaderstyle; }
set { SetCurrentValue(nameof(MLeaderstyle), ref mleaderstyle, value); }
}
// private methods (using of Reflection to work with properties names)
private void Initialize(string propName, DataItemCollection collection)
{
var curProp = GetType().GetProperty(propName);
curProp.SetValue(this, collection.CurrentItem, null);
collection.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(collection.CurrentItem))
curProp.SetValue(this, collection.CurrentItem, null);
};
}
private void SetCurrentValue(string propName, ref ICustomTypeDescriptor descriptor, ICustomTypeDescriptor value)
{
if (value != null && (IDataItem)descriptor != (IDataItem)value)
{
descriptor = value;
OnPropertyChanged(propName);
var doc = AcAp.DocumentManager.MdiActiveDocument;
using (doc.LockDocument())
{
var db = doc.Database;
db.GetType().GetProperty(propName).SetValue(db, ((IDataItem)value).ObjectId, null);
doc.Editor.WriteMessage($"\n{propName} = {((INamedValue)value).Name}");
}
}
}
}
}