public static BindSharedParamResult BindSharedParam(
Document doc,
Category cat,
string paramName,
string grpName,
ParameterType paramType,
bool visible,
bool instanceBinding)
{
try // generic
{
Application app = doc.Application;
// This is needed already here to
// store old ones for re-inserting
CategorySet catSet = app.Create.NewCategorySet();
// Loop all Binding Definitions
// IMPORTANT NOTE: Categories.Size is ALWAYS 1 !?
// For multiple categories, there is really one
// pair per each category, even though the
// Definitions are the same...
DefinitionBindingMapIterator iter
= doc.ParameterBindings.ForwardIterator();
while( iter.MoveNext() )
{
Definition def = iter.Key;
ElementBinding elemBind
= (ElementBinding) iter.Current;
// Got param name match
if( paramName.Equals( def.Name,
StringComparison.CurrentCultureIgnoreCase ) )
{
// Check for category match - Size is always 1!
if( elemBind.Categories.Contains( cat ) )
{
// Check Param Type
if( paramType != def.ParameterType )
return BindSharedParamResult.eWrongParamType;
// Check Binding Type
if( instanceBinding )
{
if( elemBind.GetType() != typeof( InstanceBinding ) )
return BindSharedParamResult.eWrongBindingType;
}
else
{
if( elemBind.GetType() != typeof( TypeBinding ) )
return BindSharedParamResult.eWrongBindingType;
}
// Check Visibility - cannot (not exposed)
// If here, everything is fine,
// ie already defined correctly
return BindSharedParamResult.eAlreadyBound;
}
// If here, no category match, hence must
// store "other" cats for re-inserting
else
{
foreach( Category catOld
in elemBind.Categories )
catSet.Insert( catOld ); // 1 only, but no index...
}
}
}
// If here, there is no Binding Definition for
// it, so make sure Param defined and then bind it!
DefinitionFile defFile
= GetOrCreateSharedParamsFile( app );
DefinitionGroup defGrp
= GetOrCreateSharedParamsGroup(
defFile, grpName );
Definition definition
= GetOrCreateSharedParamDefinition(
defGrp, paramType, paramName, visible );
catSet.Insert( cat );
InstanceBinding bind = null;
if( instanceBinding )
{
bind = app.Create.NewInstanceBinding(
catSet );
}
else
{
bind = app.Create.NewTypeBinding( catSet );
}
// There is another strange API "feature".
// If param has EVER been bound in a project
// (in above iter pairs or even if not there
// but once deleted), Insert always fails!?
// Must use .ReInsert in that case.
// See also similar findings on this topic in:
// http://thebuildingcoder.typepad.com/blog/2009/09/adding-a-category-to-a-parameter-binding.html
// - the code-idiom below may be more generic:
if( doc.ParameterBindings.Insert(
definition, bind ) )
{
return BindSharedParamResult.eSuccessfullyBound;
}
else
{
if( doc.ParameterBindings.ReInsert(
definition, bind ) )
{
return BindSharedParamResult.eSuccessfullyBound;
}
else
{
return BindSharedParamResult.eFailed;
}
}
}
catch( Exception ex )
{
MessageBox.Show( string.Format(
"Error in Binding Shared Param: {0}",
ex.Message ) );
return BindSharedParamResult.eFailed;
}
}