【发布时间】:2014-01-19 18:57:09
【问题描述】:
所以,我正在尝试设计尽可能简约的 UI,为此,我需要在文本框中提供提示,就像 android 一样。我找到了许多解决问题的方法(参见Watermark / hint text / placeholder TextBox in WPF、How can I add a hint text to WPF textbox?),但每个解决方案似乎都使用了大量的 XAML 代码、样式、触发器和排序。我想要做的是,我想要一个文本框子类,它有一个可以在任何地方使用的 HintText 属性,但到目前为止,我还没有设法接近。这是我得到的最接近的:
<TextBox x:Class="MyProgram.CustomControls.HintTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Text="ASDF"
d:DesignHeight="174" d:DesignWidth="708">
<TextBox.Resources>
<VisualBrush x:Key="VB">
<VisualBrush.Visual>
<Label Content="{Binding Path=HintText}" Foreground="LightGray" FontSize="25"/>
</VisualBrush.Visual>
</VisualBrush>
</TextBox.Resources>
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="Background" Value="{StaticResource VB}"/>
</Style>
</TextBox.Style>
</TextBox>
和:
public partial class HintTextBox : TextBox
{
public HintTextBox()
{
InitializeComponent();
}
public static DependencyProperty HintTextProperty = DependencyProperty.Register("HintText", typeof(String), typeof(HintTextBox));
}
缺少触发器定义,但这不是这里的主要问题。我的主要问题是我似乎无法绑定 HintText 属性。我无法通过 XAML 分配它,并且由于某种原因我无法绑定到它。我还尝试绑定到 TextBox 自己的 Text 属性,以查看它是否可以工作,但它没有。我究竟做错了什么?还是我完全找错了树?
编辑:我也需要 PasswordBox 具有相同的功能,但也无济于事......为什么他们仍然将 TextBox 和 PasswordBox 分开?
【问题讨论】:
-
我推荐你使用extended WPF Toolkit。它是开源的,附带
WatermarkTextBox。 -
太好了,谢谢!不过,仍然缺少密码框...
-
RE:无法绑定到您的 HintText 属性...您缺少属性定义(对依赖属性定义的补充)。公共字符串 HintText { get { return (string)GetValue(HintTextProperty); } set { SetValue(HintTextProperty, value); } }
-
你知道,我认为 clr 属性只是一种速记,不知道它是强制性的。这解决了它(无论如何它的一部分),谢谢!