C# Text返回空字符串

C# Text返回空字符串,c#,wpf,xaml,C#,Wpf,Xaml,我学习C#已经有几天了,但我遇到了一个奇怪的问题。我在WPF应用程序中有一个文本框,它正常工作时没有任何问题,但在我在XAML中将自定义模板应用到它之后,它停止返回文本值。它总是空字符串 我的XAML模板: <ControlTemplate x:Key="TextBoxBaseControlTemplate" TargetType="{x:Type TextBoxBase}"> <Border x:Name="B

我学习C#已经有几天了,但我遇到了一个奇怪的问题。我在WPF应用程序中有一个文本框,它正常工作时没有任何问题,但在我在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"/>


如何解决此问题?

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

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

<TextBox Text="{TemplateBinding Text}" .../>
还请注意,
TextBoxBase
未指定
Text
属性,因此此处应首选模板化
TextBox

<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>