2009-07-27 125 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”属性设置。