【问题标题】:WPF TextBox with Hint As Custom/User Control带有提示的 WPF 文本框作为自定义/用户控件
【发布时间】:2014-01-19 18:57:09
【问题描述】:

所以,我正在尝试设计尽可能简约的 UI,为此,我需要在文本框中提供提示,就像 android 一样。我找到了许多解决问题的方法(参见Watermark / hint text / placeholder TextBox in WPFHow 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 属性只是一种速记,不知道它是强制性的。这解决了它(无论如何它的一部分),谢谢!

标签: c# .net wpf xaml textbox


【解决方案1】:

问题是,VisualBrush资源“VB”可以在所有元素之间共享,标签内容不能绑定。

您可以尝试使用我的示例TextBox with null text hint

【讨论】:

  • 很抱歉是个菜鸟,但您愿意详细说明一下吗?
  • 好的,我会尝试 :-) 您将“VB”VisualBrush 定义为资源。在 WPF 中,每个资源(样式、颜色等)都是共享的。所以,当我们第一次使用这个资源时,VisualBrush 中的 Label 就被创建了。此标签仅创建一次并用于所有文本框。这就是为什么绑定不起作用的原因。
  • 谢谢,我现在明白了!但是我该如何解决呢?
  • 嗨,我为错误的答案道歉。我以为您将 HintTextbox 作为 CustomControl 而不是作为 UserControl。所以如果你想从 VisualBruh 绑定标签的内容,你必须使用 RelativeSource 绑定。 {Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type my:HintTextBox}}, Path=HintText}" my 是 HintTextBox 的命名空间。但我仍然认为,正确的解决方案是使用自定义控件和模板,这我在样本code.msdn.microsoft.com/TextBox-with-null-text-hint-0b384543
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多