Creating a custom control that is a Button that also has a Items and ItemsSource?
-
06-07-2019 - |
Question
I'm trying to create a SplitButton
control that uses a ContextMenu
to display its items. The SplitButton
is currently deriving from Button
. I have a PART_DropDownInitiator
that is the little icon the user clicks on to bring up the ContextMenu
for the SplitButton
to show its items.
The problem is that I'm trying to setup a default ContextMenu
inside of the SplitButton
's Template
or style, this way the user of the control doesn't have to do it themselves. At first I figured I'd just have the user just set the SplitButton.ContextMenu.Items
property in xaml, but that doesn't appear to be possible. Now I'd like to add an Items
and ItemsSource
properties to the SplitButton
that the ContextMenu
within the SplitButton
's template can bind to it. And the user should than just have to set the Items
or ItemsSource
property in xaml or code-behind on the SplitButton
...
But, both the Items
and ItemsSource
properties seem to originate from ItemsControl
, which is a problem because the SplitButton
is already deriving from Button
. So I'm not sure what to do... Any ideas?
Solution
If you're going the inheritance route, you should derive from HeaderedItemsControl instead, where your default ControlTemplate puts the Header content as the contents of a Button.
As a result, you also get Items/ItemsSource -- the only thing you have to develop is your ControlTemplate.
Lastly, consider implementing the menu portion as a Popup instead of a ContextMenu. ContextMenu's are a purpose-specific UI element (and generally brought up with a right-click). For more information, see the default ControlTemplate of ComboBox in aero.normalcolor.xaml.