【问题标题】:Using DependencyProperty to Display Placeholder Text on a TextBox (UWP)使用 DependencyProperty 在文本框 (UWP) 上显示占位符文本
【发布时间】:2020-08-17 06:29:35
【问题描述】:

我有一个只包含一个文本框的自定义用户控件,我希望能够将占位符文本绑定到该文本框。我的 UserControl 代码是这样的

<UserControl
x:Class="Proj.Editors.EditTextControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MemberSuiteConsoleApp.Controls.Editors"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid>
    <TextBox x:Name="txtbox"  Width="300" PlaceholderText="{Binding ElementName=txtbox, Path=DataContext.PlaceholderText}"></TextBox>
</Grid>

public sealed partial class EditTextControl : UserControl
    {
        public EditTextControl()
        {
            this.InitializeComponent();
        }

        public string PlaceholderText
        {
            get { return (string)GetValue(PlaceholderTextProperty); }
            set { SetValue(PlaceholderTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for PlaceholderText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PlaceholderTextProperty =
            DependencyProperty.Register("PlaceholderText", typeof(string), typeof(EditTextControl), new PropertyMetadata(""));

    }

我正在尝试在我的页面中使用此 UserControl,就像在我的页面中一样

 <Grid>
    <editors:EditTextControl PlaceholderText="My placeholder" Height="400"></editors:EditTextControl>
</Grid>

但由于某种原因,占位符文本没有显示在文本框中,我在这里缺少什么?

【问题讨论】:

  • 通常我会使用转换器生成占位符文本。 VM 的值为 null、空字符串等将与占位符文本相关。
  • @Christopher 占位符是一个开始我也有很多其他属性来建立依赖关系,这就是为什么我要先解决一个。所以我可以为其他人遵循这个过程
  • 没有什么能阻止您在多个绑定上使用一个转换器。只要所有这些属性都有相同的方式来标注“无值”或“等待用户输入”,就是这样。
  • 好的。在您的第一条评论中,您谈到了 VM 的值为 NULL,但在我的情况下,我直接在 XAML 本身中分配占位符文本,它会受到 VM 值的影响吗?
  • 我什至没有意识到它有一个属性,但我应该猜到了。当然,您不需要转换器:docs.microsoft.com/en-us/uwp/api/… 至少在我阅读属性描述时,只要值不更改,就应该显示 PlaceHolder 文本。可能的意思是“改变了最初检索的绑定”。我不确定它会对用户删除输入之类的东西做出什么反应(即使这不会恢复确切的起始值)。

标签: c# xaml uwp dependency-properties


【解决方案1】:

您可以改用 x:Bind。我试过了。

<TextBox x:Name="txtbox"  Width="300" PlaceholderText="{x:Bind PlaceholderText, Mode=OneWay}"></TextBox>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-07
    • 2016-09-14
    • 2017-12-03
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2018-10-30
    相关资源
    最近更新 更多