ビュー内で要素が可視かどうかを知る最も信頼できる方法は、そのビューに固有のFilteredElementCollectorを使用することです。要素の可視性を制御する方法は非常に多くあり、これを他の方法で判断しようとすると実用的ではありません。
これを達成するために私が使用するユーティリティ機能は以下のとおりです。これはファミリインスタンスだけでなく、どの要素でも機能することに注意してください。
public static bool IsElementVisibleInView([NotNull] this View view, [NotNull] Element el)
{
if (view == null)
{
throw new ArgumentNullException(nameof(view));
}
if (el == null)
{
throw new ArgumentNullException(nameof(el));
}
// Obtain the element's document
Document doc = el.Document;
ElementId elId = el.Id;
// Create a FilterRule that searches for an element matching the given Id
FilterRule idRule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInParameter.ID_PARAM), elId);
var idFilter = new ElementParameterFilter(idRule);
// Use an ElementCategoryFilter to speed up the search, as ElementParameterFilter is a slow filter
Category cat = el.Category;
var catFilter = new ElementCategoryFilter(cat.Id);
// Use the constructor of FilteredElementCollector that accepts a view id as a parameter to only search that view
// Also use the WhereElementIsNotElementType filter to eliminate element types
FilteredElementCollector collector =
new FilteredElementCollector(doc, view.Id).WhereElementIsNotElementType().WherePasses(catFilter).WherePasses(idFilter);
// If the collector contains any items, then we know that the element is visible in the given view
return collector.Any();
}
カテゴリフィルタは、低速パラメータフィルタを使用して目的の要素を見つける前に、目的のカテゴリ以外の要素を削除するために使用されます。おそらくフィルタの賢明な使い方でこれをさらにスピードアップすることは可能ですが、私はそれが実際には十分に速いことがわかりました。
ReSharperをお持ちでない場合は、表示されている[NotNull]アノテーションを削除してください。
ありがとう、コリン!私はそれを[The Building Coder samples](https://github.com/jeremytammik/the_building_coder_samples)[CmdViewsShowingElements](https://github.com/jeremytammik/the_building_coder_samples/blob/master/BuildingCoder/BuildingCoder/CmdViewsShowingElements.cs)に追加しました。 )、[要素を示すビューの決定](http://thebuildingcoder.typepad.com/blog/2016/12/determining-views-showing-an-element.html)の説明で説明しています。 –
私はこのディスカッションと、Building Coderの以前の関連する問題のいくつかの指摘も要約しました:[ビューで表示される要素の取得](http://thebuildingcoder.typepad.com/blog/2017/05/retrieving-elements-visible-in- view.html)。再びThx! –