In one of my WPF project, I have integrated WPF Toolkit's AutoCompleteBox
control. I need a custom Context Menu
for this control and I have added one using the ContextMenu
property. Unfortunately its not showing the custom created one but showing the default one (i.e. Cut, Copy, Paste with Cut & Copy as disabled).
To recreate the issue, I have created a sample project and the window contains 2 controls inside a Grid
.
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<toolkit:AutoCompleteBox>
<toolkit:AutoCompleteBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Menu Item 1"></MenuItem>
<MenuItem Header="Menu Item 2"></MenuItem>
</ContextMenu>
</toolkit:AutoCompleteBox.ContextMenu>
</toolkit:AutoCompleteBox>
<TextBox Grid.Row="1" >
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="Menu Item 1"></MenuItem>
<MenuItem Header="Menu Item 2"></MenuItem>
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</Grid>
The two controls have the same ContextMenu
and if I run the solution, I can see that the custom created ContextMenu
is working for TextBox
and not for AutoCompleteBox
.
Also, I set the same Context Menu to Grid (parent control) and set ContextMenu="{x:Null}"
to TextBox & AutoCompleteBox
. Now the ContextMenu
is inherited for TextBox
but not for AutoCompleteBox
.
So my question is, how can I create a custom ContextMenu
for AutoCompleteBox?
If it is not by design(AutoCompleteBox
), how can I add a ContextMenu
to a custom AutoCompleteBox control which is inherited from AutoCompleteBox
.
Please advice.
AutoCompleteBox
exposes dependency property TextBoxStyle
which you can set to customize TextBox hosted inside AutoCompleteBox
.
Another approach would be to provide your own template which i would strongly oppose since this DP is provide explicitly for the purpose you want i.e. to customize textBox from outside.
Create a style for TextBox with your custom ContextMenu and apply that template both on your TextBox and AutoCompleteBox. This sample is working fine -
<Grid>
<Grid.Resources>
<Style x:Key="CustomStyle" TargetType="TextBox"
BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Header1"/>
<MenuItem Header="Header2"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<toolkit:AutoCompleteBox TextBoxStyle="{StaticResource CustomStyle}"/>
<TextBox Grid.Row="1" Style="{StaticResource CustomStyle}"/>
</Grid>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With