2009-07-27 29 views
13

我有這個TextBox。該文本框位於的DataTemplatewpf:選擇文本框中的文本與IsReadOnly = true?

<DataTemplate x:Key="myTemplate"> 
    <TextBox Text="{Binding Path=FullValue, Mode=TwoWay}" IsEnabled="False" /> 
     ... 

,我想允許用戶選擇它裏面的全部文本(可選通過點擊文本框)。我不想使用任何 代碼。

如何做到這一點?提前致謝。

+0

我使用了`SelectAll()`,然後它使您可以右鍵單擊並複製內容。 – EricG 2015-01-15 12:01:45

回答

18

使用IsReadOnly屬性而不是IsEnabled允許用戶選擇文本。另外,如果它不應該被編輯,OneWay綁定應該是足夠的。

XAML的思想並不是完全替代代碼隱藏。最重要的是你試圖在代碼隱藏中只使用UI特定的代碼,而不是業務邏輯。這就是說,選擇所有文本是特定於UI的,並且不會在代碼隱藏中受到傷害。使用myTextBox.SelectAll()。

+0

那麼問題是,這個位於DataTemplate中。而我所知道的事件不能用在DataTemplates中。 – 2009-07-27 07:25:06

6

刪除IsEnabled並將TextBox設置爲ReadOnly將允許您選擇文本但停止用戶輸入。

IsReadOnly="True" 

用這種方法唯一的問題是,雖然你將無法在「已啓用」文本框還是會期待類型。爲了避免這種情況發生(如果你想?),你可以添加一個樣式來減輕文字並使背景變暗(使其看起來不能使用)。

我已經添加了以下示例,其樣式會在禁用和啓用外觀之間彈出文本框。

<Window x:Class="WpfApplication1.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Window1" Height="300" Width="300"> 
<Window.Resources> 
    <Style TargetType="{x:Type TextBox}"> 

     <Style.Triggers> 
      <Trigger Property="IsReadOnly" Value="True"> 
       <Setter Property="Background" Value="LightGray" /> 
      </Trigger> 
      <Trigger Property="IsReadOnly" Value="True"> 
       <Setter Property="Foreground" Value="DarkGray" /> 
      </Trigger> 
      <Trigger Property="IsReadOnly" Value="False"> 
       <Setter Property="Background" Value="White" /> 
      </Trigger> 
      <Trigger Property="IsReadOnly" Value="False"> 
       <Setter Property="Foreground" Value="Black" /> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</Window.Resources> 
<Grid> 
    <TextBox Height="23" Margin="25,22,133,0" IsReadOnly="True" Text="monkey" Name="textBox1" VerticalAlignment="Top" /> 
    <Button Height="23" Margin="25,51,133,0" Name="button1" VerticalAlignment="Top" Click="button1_Click">Button</Button> 
</Grid> 

private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     textBox1.IsReadOnly = !textBox1.IsReadOnly; 
    } 
4

一個說明我剛發現(顯然這是一個老問題,但是這可能幫助別人):

如果IsHitTestVisible=False然後選擇(因此複製)也將被禁用。

0

稍加修改例子 - 要匹配的WinForms的風格(沒有創造您自己的新風格)

By adding <Window.Resources> after <Window> and before <Grid> will make your text box behave like normal winforms textbox. 


<Window x:Class="..." Height="330" Width="600" Loaded="Window_Loaded" WindowStartupLocation="CenterOwner"> 

<Window.Resources> 
    <Style TargetType="{x:Type TextBox}"> 
     <Style.Triggers> 
      <Trigger Property="IsReadOnly" Value="True"> 
       <Setter Property="Background" Value="LightGray" /> 
      </Trigger> 
      <Trigger Property="IsReadOnly" Value="False"> 
       <Setter Property="Background" Value="White" /> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</Window.Resources> 

<Grid> 

當然你的文本必須有IsReadOnly =「true」屬性設置。