我有这个文本框。 该文本框位于的DataTemplate:
<DataTemplate x:Key="myTemplate">
<TextBox Text="{Binding Path=FullValue, Mode=TwoWay}" IsEnabled="False" />
...
我想允许用户选择它里面的全部文本(可选通过点击文本框)。 我不想后面使用任何代码。
怎么做? 提前致谢。
我有这个文本框。 该文本框位于的DataTemplate:
<DataTemplate x:Key="myTemplate">
<TextBox Text="{Binding Path=FullValue, Mode=TwoWay}" IsEnabled="False" />
...
我想允许用户选择它里面的全部文本(可选通过点击文本框)。 我不想后面使用任何代码。
怎么做? 提前致谢。
使用IsReadOnly属性代替的IsEnabled允许用户选择文本。 另外,如果它不应该被编辑,单向绑定就足够了。
XAML的想法是不完全替代代码隐藏。 最重要的是,你尝试在后台代码,而不是业务逻辑只有特定的用户界面代码。 话虽这么说,选择所有文字UI特有的,并在代码隐藏不受到伤害。 使用myTextBox.SelectAll()来。
删除的IsEnabled和设置文本框为只读将允许您选择文本,但阻止用户输入。
IsReadOnly="True"
这种方法唯一的问题是,虽然你将无法在TextBox它仍然看起来键入“已启用”。
为了得到一轮(如果你想?),你只需添加一个样式,以减轻文字和变暗的背景(使它看起来禁用)。
我已经添加了一个风格,将轻弹禁用和启用的外观之间的文本框下面的例子。
<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;
}
一个说明我刚发现(显然这是一个老问题,但是这可能帮助别人):
如果IsHitTestVisible=False
然后选择(因此复制)也被禁止。
稍加修改例子 - 要匹配的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”属性设置。