WPF TextBox选中的文本不起作用

时间:2017-07-25 09:11:46

标签: c# wpf textbox

我有一个带有静态资源的只读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中存在正确的文本。

1 个答案:

答案 0 :(得分:0)

将数据绑定到ListBoxItem,然后从ListBoxItem调用数据。然后整个ListBoxItem是可选择的。 e.g。

<ListBox SelectionChanged="ListItemSelected" ItemTemplate="{StaticResource SelectedTextTemplate}">  
    <ListBox.ItemContainerStyle>

        <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
           .../...
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

在ListBox之外构建数据模板或控件模板,例如

<DataTemplate x:Key="SelectedTextTemplate">
      <TextBox Text="{Binding SelectedText}"/>
</DataTemplate>