我想最好使用样式禁用文本框中的文本选择。原因是我有一种风格,它使文本框看起来像一个文本块,直到满足某个标准(IsRenaming)。这些是树视图的节点,所以我不希望用户能够选择文本。这是样式:
<Style x:Key="TextBlockStyleForTextBox" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="IsReadOnly" Value="True" />
</Style>
<Style x:Key="RenamingTextBox" TargetType="{x:Type TextBox}" BasedOn="{StaticResource TextBlockStyleForTextBox}">
<Setter Property="Cursor" Value="Arrow"/>
<Setter Property="Padding" Value="0" />
<Setter Property="Margin" Value="0" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsRenaming}" Value="true">
<DataTrigger.Setters>
<Setter Property="TextBox.IsReadOnly" Value="False" />
<Setter Property="Cursor" Value="IBeam" />
<Setter Property="Background" >
<Setter.Value>
<SolidColorBrush Color="{DynamicResource WhiteColor}"/>
</Setter.Value>
</Setter>
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="2" />
<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
<Setter Property="behaviors:TextBoxBehavior.SelectAll" Value="True"/>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
我认为我不会在任何地方覆盖 IsReadOnly。这是我的文本框定义:
<DataTemplate x:Key="MyTemplate" >
<TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=TreeView}}"
Style="{StaticResource RenamingTextBox}">
... ETC