修复了TextBox中的文本

时间:2012-04-27 15:46:05

标签: c# wpf textbox

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

例如,CMD中的路径:

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

4 个答案:

答案 0 :(得分: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>

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

答案 1 :(得分:0)

当您动态填充文本时,

TextBox IsReadOnly = true?如果你使用MVVM将IsReadOnly绑定到ViewModel中的属性,那么当ViewModel填充文本时

答案 2 :(得分:0)

您可以使用文本块。 如果您必须使用文本框,则可以执行此操作只读将IsReadOnly属性更改为“True”

答案 3 :(得分:-2)

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (textBox1.SelectionStart < LengthOfFixedString)
        e.SuppressKeyPress = true;
}