展開可能なボタンのようなものを作成しようとしています-マウスの左ボタンをクリックすると開くコンテキストメニューが上にあるボタン。ContextMenu
私がまだ仕上げることができないのは、コントロールのように WPF XAML デザイナーで設定できる項目プロパティだけです。したがって、私が理解できる限り、それはItemCollection
自分のプロパティにタイプを使用する必要があることを意味します。Ok。私のコンポーネントを見てみましょう:
public partial class MenuButton : Button
{
private readonly ContextMenu Menu;
public static readonly DependencyProperty MenuItemsProperty =
DependencyProperty.Register("MenuItems", typeof(ItemCollection), typeof(ContextMenu), new PropertyMetadata(default(ItemCollection), new PropertyChangedCallback(OnSomeMenuItemsPropertyChanged)));
public ItemCollection MenuItems
{
get => (ItemCollection)GetValue(MenuItemsProperty);
set => SetValue(MenuItemsProperty, value);
}
public MenuButton()
{
MenuItems = new DataGrid().Items; // I really need to do it - otherwise I'll get an error
Menu = new ContextMenu
{
HasDropShadow = false,
PlacementTarget = this,
Placement = PlacementMode.Top,
};
InitializeComponent();
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
Menu.Width = ActualWidth;
Menu.IsOpen = true;
}
private static void OnSomeMenuItemsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
if (target is ContextMenu menu)
{
menu.ItemsSource = (ItemCollection)e.NewValue;
}
}
}
しかし、「キャッチ」できませんOnSomeMenuItemsPropertyChanged
-ブレークポイントはここでは機能しません。つまり、このメカニズムが間違っているということです。どうすれば修正できますか?プロパティの変更を処理するには、( for のように) 代わりにOnItemsChanged
andイベントを使用する必要がありますか? それとも何か他のものですか?OnItemsCollectionChanged
ObservableCollection