独自のコンテキストメニューを備えたユーザーコントロールがありますが、そのメニューに項目を追加する必要があります。
私が採用したアプローチは、ContextMenuItemsと呼ばれる依存関係プロパティを持つことでした。
Public Shared ReadOnly ContextMenuItemsProperty As DependencyProperty = DependencyProperty.Register("ContextMenuItems", GetType(ObservableCollection(Of MenuItem)), GetType(SmartDataControl), New FrameworkPropertyMetadata(New ObservableCollection(Of MenuItem)))
Public Property ContextMenuItems As ObservableCollection(Of MenuItem)
Get
Return GetValue(ContextMenuItemsProperty)
End Get
Set(ByVal value As ObservableCollection(Of MenuItem))
SetValue(ContextMenuItemsProperty, value)
End Set
End Property
次に、CompositeCollectionを使用して、コントロールの静的メニュー項目をホストから提供されたリストと組み合わせました。
<CompositeCollection x:Key="MenuItemsCompositeCollection">
<MenuItem Header="TEST" />
<CollectionContainer Collection="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ContextMenuItems, Converter={StaticResource TestConverter}}" />
<MenuItem Header="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ContextMenuItems}" />
</CompositeCollection>
そのリソースにバインドすると、次のように表示されます。
- テスト
- (コレクション)
2番目のメニュー項目は、コレクションにバインドされており、アクセスできることを証明しています。メニュー項目に追加したテストコンバーターがあり、コンバーターメソッドで壊れますが、コンバーターをCollectionContainerに追加しても呼び出されません。
最後に、出力ウィンドウに次のエラーが表示されます。
System.Windows.Dataエラー:4:参照'RelativeSource FindAncestor、AncestorType ='System.Windows.Controls.UserControl'、AncestorLevel='1''でバインドするためのソースが見つかりません。BindingExpression:Path = ContextMenuItems; DataItem = null; ターゲット要素は'CollectionContainer'(HashCode = 41005040); ターゲットプロパティは「コレクション」(タイプ「IEnumerable」)です。