簡體   English   中英

TextBox.Text 返回空字符串

[英]TextBox.Text returns empty string

我花了幾天時間學習 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"/>

我怎樣才能解決這個問題?

創建模板包括需要指定在哪里可以找到原始屬性。 因此 XAML 提供了TemplateBinding ,它允許將模板化控件的屬性綁定到您定義的內容。

顯而易見的解決方案是只使用標記擴展來綁定文本,例如:

<TextBox Text="{TemplateBinding 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>

另請注意, TextBoxBase未指定Text屬性,因此此處應首選模板TextBox

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM