【问题标题】:TextBox.Text returns empty stringTextBox.Text 返回空字符串
【发布时间】:2020-06-21 15:50:37
【问题描述】:

我学习 C# 已经有几天了,但我遇到了一个奇怪的问题。我在 WPF 应用程序中有一个 TextBox,它通常可以正常工作,但是在我在 XAML 中对其应用自定义模板后,它会停止返回文本值。它总是空字符串。

我在 XAML 中的模板:

<ControlTemplate x:Key="TextBoxBaseControlTemplate" TargetType="{x:Type TextBoxBase}">
        <Border x:Name="Bd" BorderBrush="DarkGray" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4,4,4,4">
            <TextBox Background="#353535" Foreground="White"/>
        </Border>
    </ControlTemplate>

我在 XAML 中的文本框:

<TextBox x:Name="TextBox" Template="{StaticResource TextBoxBaseControlTemplate}" Foreground="White" BorderThickness="1" BorderBrush="DarkGray" HorizontalAlignment="Stretch" Height="23" Margin="53,0,105,15" TextWrapping="Wrap" Text="Enter city" VerticalAlignment="Bottom" GotFocus="TextBox_GotFocus" KeyDown="TextBox_KeyDown"/>

我该如何解决这个问题?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    创建模板需要指定在何处查找原始属性。因此 XAML 提供了TemplateBinding,它允许将模板化控件的属性绑定到您定义的内容。

    显而易见的解决方案是只使用标记扩展来绑定文本,例如:

    <TextBox Text="{TemplateBinding Text}" .../>
    

    不幸的是,这在TextBox 的情况下效果不佳,如中所述 this question。解决方案是通过那里描述的相对源绑定。因此,您的模板应如下所示,以提供预期的文本:

    <ControlTemplate x:Key="TextBoxBaseControlTemplate" TargetType="{x:Type TextBox}">
        <Border x:Name="Bd" BorderBrush="DarkGray" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4,4,4,4">
            <TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, UpdateSourceTrigger=PropertyChanged}"
                     Background="#353535" Foreground="White"/>
        </Border>
    </ControlTemplate>
    

    另请注意,TextBoxBase 未指定 Text 属性,因此此处应首选模板化 TextBox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2020-07-11
      • 2015-05-25
      • 2011-05-09
      • 1970-01-01
      • 2012-07-20
      • 2011-12-15
      相关资源
      最近更新 更多