【发布时间】:2017-07-25 09:11:45
【问题描述】:
我有一个带有静态资源的只读 TextBox 控件,如下所示:
<Style TargetType="TextBox" x:Key="MyEditTextEditor">
<Setter Property="FontFamily" Value="{Binding Path=TextEditorFontFamily, ElementName=LogViewerProperty}" />
<Setter Property="FontWeight" Value="{Binding Path=TextEditorFontWeight, ElementName=LogViewerProperty}" />
<Setter Property="FontSize" Value="{Binding Path=TextEditorFontSize, ElementName=LogViewerProperty}" />
<Setter Property="FontStyle" Value="{Binding Path=TextEditorFontStyle, ElementName=LogViewerProperty}" />
<Setter Property="TextWrapping" Value="{Binding Path=WordWrapping, ElementName=LogViewerProperty, Converter={StaticResource BoolToTextWrap}}" />
<Setter Property="Text" Value="{Binding Message, Mode=OneWay}" />
<Setter Property="IsReadOnly" Value="True" />
<Setter Property="Visibility" Value="Collapsed" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Grid>
<TextBox Text="{TemplateBinding Text}" BorderThickness="0" Margin="-3,-1"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}" Value="True">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Opacity="0.4" Color="{Binding Source={x:Reference LogViewerProperty}, Path=TextEditorSelectionColor}" />
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
它嵌入到 ListBox 中。一切正常,但是当我想获取选定的文本时,该属性始终是 string.Empty。 SelectionChanged 事件完美运行。有什么建议么?目前我不知道,为什么 SelectedText 是 string.Empty。
这是 SelectionChanged 事件
private void ReadOnlyEditor_SelectionChanged(object sender, RoutedEventArgs e)
{
LOG.Debug("Current text {3}; selection {0} length {1}, start {2}", readOnlyEditor.SelectedText, readOnlyEditor.SelectionLength, readOnlyEditor.SelectionStart, readOnlyEditor.Text);
}
是的,文本在控件中被选中,但属性为空。在 readOnlyEditor.Text 中存在正确的文本。
【问题讨论】:
-
SelectedText 是按字面选择的文本。如突出显示的文本。如果未选择任何内容,则它将返回空字符串。你确定你不只是想要文本吗?
-
您是否尝试过将模板中TextBox的
SelectedText绑定到SelectedText?如模板 TextBox 上的SelectedText="{TemplateBinding SelectedText}"。 -
不幸的是 SelectedText 不是依赖属性 - 这种绑定是不可能的。
-
我怀疑在 TextBox 的 ControlTemplate 中有一个 TextBox 是一个聪明的主意。
-
啊,这是一个很好的提示,谢谢!我将 ControlTemplate 部分注释掉并再次尝试。现在可以了!