user181813
user181813

Reputation: 1891

Hiding the right click menu of an unfocusable WPF textbox

In the WPF application below, you get a cut/copy/paste right-click menu when you right click the text box, regardless if the text box is focusable or not. I would like the right-click menu to be shown only if the text box is focusable. Do you know how to do this?

<Window x:Class="TextBoxApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Button Click="Button_OnClick"></Button>
            <TextBox Focusable="False" Name="myTextBox"></TextBox>
        </StackPanel>
    </Grid>
</Window>

using System.Windows;  
using System.Windows.Input;

namespace TextBoxApp  
{    
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_OnClick(object sender, RoutedEventArgs e)
        {
            myTextBox.Focusable = !myTextBox.Focusable;
        }
    }
}

Upvotes: 2

Views: 1874

Answers (2)

Myrtle
Myrtle

Reputation: 5831

If you would not like to be able to focus it, i Think using the

uiElement.IsHitTestVisible = false;

property will also prevent you from showing the context menu. It is an dependency property so you can choose to bind it to the Focusable property.

I think this is preferred over just targeting the ContextMenu as I assume your functional requirement is to be unable to do anything with the textbox at all.

In response to @Dr. Andrew Burnett-Thompson I made the following Xaml example:

    <TextBox Focusable="False">
        <TextBox.Style>
            <Style TargetType="TextBox">
                <Style.Triggers>
                    <Trigger Property="Focusable" Value="False">
                        <Setter Property="IsHitTestVisible" Value="False"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

Upvotes: 3

Bas
Bas

Reputation: 27095

You can set the visibility of the TextBox's ContextMenu to Hidden when the textbox is not focusable using a trigger in XAML:

 <TextBox Name="textBox1" Focusable="False">
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <Trigger Property="Focusable" Value="false">
                            <Setter Property="ContextMenu.Visibility" Value="Hidden" />
                        </Trigger>                        
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>

Upvotes: 3

Related Questions