0

如何将固定文本动态添加到 TextBox?“固定文本”是指用户输入无法删除的文本。

例如 CMD 中的路径:

C:\Program Files>cd ..
C:\>
4

4 回答 4

2

我假设您想要一个可编辑的文本框,它的开头有一些用户无法编辑的固定文本。如果是这样,那么这似乎可行 - 它基于 Blend 中提取的标准文本框样式...

您需要在您的 xaml 根目录中有以下命名空间声明:

     xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"

然后使用这个模板:

    <ControlTemplate TargetType="{x:Type TextBox}">
        <Microsoft_Windows_Themes:ListBoxChrome x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}" SnapsToDevicePixels="true">
        <StackPanel Orientation="Horizontal">
            <TextBlock VerticalAlignment="Center">This is fixed:</TextBlock>
            <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
          </StackPanel>
    </Microsoft_Windows_Themes:ListBoxChrome>
    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

如果要将其包装在自定义控件或用户控件中,则可以通过自定义属性以编程方式设置固定文本。

于 2012-04-27T15:57:25.903 回答
0

动态填充文本时 TextBox IsReadOnly = true?如果您使用 MVVM 将 IsReadOnly 绑定到 ViewModel 中的属性,则当该 ViewModel 填充文本时

于 2012-04-27T15:50:48.717 回答
0

您可以改用文本块。如果您必须使用文本框,则可以将 IsReadOnly 属性更改为“True”

于 2012-04-27T15:51:10.633 回答
-2
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (textBox1.SelectionStart < LengthOfFixedString)
        e.SuppressKeyPress = true;
}
于 2012-04-27T15:57:48.023 回答