c# - C# WPF 中的占位符文本框 - 无法绑定 DepedencyProperty
问题描述
我试图用一些可变的占位符文本构建我的 TextBox。但是 Visual Brush - Label 中没有使用属性“PlaceholderText”。
占位符文本<Label Content="{Binding PlaceholderText}" Foreground="LightGray" />
始终为空。
当我使用 中的绑定时,绑定有效。我尝试将绑定用作 Text:<TextBox Text="{Binding PlaceholderText}" >
并且效果很好。
为什么不在里面<VisualBrush><Label Content="...">...
我希望有一个人可以帮助我。
<TextBox x:Class="CustomerPro.Common.Controls.PlaceholderTextBox"
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"
xmlns:local="clr-namespace:CustomerPro.Common.Controls"
mc:Ignorable="d"
d:DesignHeight="50" d:DesignWidth="800" Name="phTextBox">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Resources>
<VisualBrush x:Key="PHBoxBackground" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding PlaceholderText}" Foreground="LightGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="">
<Setter Property="Background" Value="{StaticResource PHBoxBackground}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource PHBoxBackground}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Background" Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
public partial class PlaceholderTextBox : TextBox
{
#region PlaceholderText
/// <summary>
/// Gets or sets the PlaceholderText which is displayed next to the field
/// </summary>
public String PlaceholderText
{
get { return (String)GetValue(PlaceholderTextProperty); }
set { SetValue(PlaceholderTextProperty, value); }
}
/// <summary>
/// Identified the PlaceholderText dependency property
/// </summary>
public static readonly DependencyProperty PlaceholderTextProperty = DependencyProperty.Register("PlaceholderText", typeof(string), typeof(PlaceholderTextBox), new PropertyMetadata("Type some Text"));
#endregion
public PlaceholderTextBox()
{
InitializeComponent();
this.phTextBox.DataContext = this;
}
}
解决方案
您需要通过 " ElementName
" 进行绑定,但这在以下内容中进行了更详细的说明Resources
:
<Label
Content="{Binding Source={x:Reference phTextBox}, Path=PlaceholderText}"
Foreground="LightGray" />
另请参阅msdn 论坛。
推荐阅读
- reactjs - 通过 react 的 useEffect 中的查询组件获取数据
- python - “未定义名称错误 [命令名称]”在 Tkinter 中使用按钮时
- javascript - 将 MongoDB 响应推送到无法正常工作的数组
- r - 为两组构建销售价格与居住面积的散点图
- asp.net - 使用 foreach 遍历列表
- python - 斐波那契数列计算器似乎是正确的,但在网上找不到类似的代码。有什么不对?
- mysql - HAVING 与子查询的效率以及原因
- java - 除非 log4j2.xml 同时在两个文件夹中,否则没有找到 log4j2 配置文件错误发生
- python - 本地主机连接被拒绝
- android - 运行 Espresso Instrumentation 测试时出现错误:“NoClassDefFoundError:解析失败:Landroidx/databinding/DataBinderMapperImpl”