2012-01-03 89 views
2

在下面的WPF應用程序中,當您右鍵單擊文本框時,無論文本框是否可調焦,都會得到剪切/複製/粘貼右鍵單擊菜單。我只想在文本框可以調焦的情況下顯示右鍵單擊菜單。你知道如何做到這一點?隱藏無焦點的WPF文本框的右鍵單擊菜單

<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; 
     } 
    } 
} 

回答

3

如果您不希望能夠集中精力了,我想用

uiElement.IsHitTestVisible = false; 

屬性還可以防止你出上下文菜單。 它是一個依賴項屬性,因此您可以選擇將其綁定到Focusable屬性。

我認爲這是優先於針對ContextMenu,因爲我認爲你的功能需求是無法對文本框做任何事情。

迴應@Dr。安德魯·伯內特 - 湯普森我做了如下的XAML示例:

<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> 
+1

我想你閱讀正確的問題,但也許使用觸發器設置IsHitTestVisible = false時IsFocusable = false可以實現這一目標? (如果確實IsHitTestVisible = false,則禁用文本框) – 2012-01-03 12:19:09

+0

IsHitTestVisibile禁用對文本框的任何輸入並觸發底層控件上的可能不需要的單擊事件行爲 – Bas 2012-01-03 13:45:44

+0

@BasB關於底層控件上的單擊事件所說的事情是不會發生在我身上的。這確實應該被考慮在內。 – Aphelion 2012-01-03 14:16:17

3

您可以設置文本框的文本菜單來隱藏可見性時的文本框使用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>