- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我如何将一些文本放入 TextBox
中,当用户在其中键入内容时该文本框会自动删除?
最佳答案
您可以创建一个水印,该水印可以添加到具有附加属性的任何 TextBox
中。这是附加属性的来源:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
/// <summary>
/// Class that provides the Watermark attached property
/// </summary>
public static class WatermarkService
{
/// <summary>
/// Watermark Attached Dependency Property
/// </summary>
public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached(
"Watermark",
typeof(object),
typeof(WatermarkService),
new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged)));
#region Private Fields
/// <summary>
/// Dictionary of ItemsControls
/// </summary>
private static readonly Dictionary<object, ItemsControl> itemsControls = new Dictionary<object, ItemsControl>();
#endregion
/// <summary>
/// Gets the Watermark property. This dependency property indicates the watermark for the control.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to get the property from</param>
/// <returns>The value of the Watermark property</returns>
public static object GetWatermark(DependencyObject d)
{
return (object)d.GetValue(WatermarkProperty);
}
/// <summary>
/// Sets the Watermark property. This dependency property indicates the watermark for the control.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> to set the property on</param>
/// <param name="value">value of the property</param>
public static void SetWatermark(DependencyObject d, object value)
{
d.SetValue(WatermarkProperty, value);
}
/// <summary>
/// Handles changes to the Watermark property.
/// </summary>
/// <param name="d"><see cref="DependencyObject"/> that fired the event</param>
/// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param>
private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Control control = (Control)d;
control.Loaded += Control_Loaded;
if (d is ComboBox)
{
control.GotKeyboardFocus += Control_GotKeyboardFocus;
control.LostKeyboardFocus += Control_Loaded;
}
else if (d is TextBox)
{
control.GotKeyboardFocus += Control_GotKeyboardFocus;
control.LostKeyboardFocus += Control_Loaded;
((TextBox)control).TextChanged += Control_GotKeyboardFocus;
}
if (d is ItemsControl && !(d is ComboBox))
{
ItemsControl i = (ItemsControl)d;
// for Items property
i.ItemContainerGenerator.ItemsChanged += ItemsChanged;
itemsControls.Add(i.ItemContainerGenerator, i);
// for ItemsSource property
DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, i.GetType());
prop.AddValueChanged(i, ItemsSourceChanged);
}
}
#region Event Handlers
/// <summary>
/// Handle the GotFocus event on the control
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e)
{
Control c = (Control)sender;
if (ShouldShowWatermark(c))
{
ShowWatermark(c);
}
else
{
RemoveWatermark(c);
}
}
/// <summary>
/// Handle the Loaded and LostFocus event on the control
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
private static void Control_Loaded(object sender, RoutedEventArgs e)
{
Control control = (Control)sender;
if (ShouldShowWatermark(control))
{
ShowWatermark(control);
}
}
/// <summary>
/// Event handler for the items source changed event
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="EventArgs"/> that contains the event data.</param>
private static void ItemsSourceChanged(object sender, EventArgs e)
{
ItemsControl c = (ItemsControl)sender;
if (c.ItemsSource != null)
{
if (ShouldShowWatermark(c))
{
ShowWatermark(c);
}
else
{
RemoveWatermark(c);
}
}
else
{
ShowWatermark(c);
}
}
/// <summary>
/// Event handler for the items changed event
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="ItemsChangedEventArgs"/> that contains the event data.</param>
private static void ItemsChanged(object sender, ItemsChangedEventArgs e)
{
ItemsControl control;
if (itemsControls.TryGetValue(sender, out control))
{
if (ShouldShowWatermark(control))
{
ShowWatermark(control);
}
else
{
RemoveWatermark(control);
}
}
}
#endregion
#region Helper Methods
/// <summary>
/// Remove the watermark from the specified element
/// </summary>
/// <param name="control">Element to remove the watermark from</param>
private static void RemoveWatermark(UIElement control)
{
AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);
// layer could be null if control is no longer in the visual tree
if (layer != null)
{
Adorner[] adorners = layer.GetAdorners(control);
if (adorners == null)
{
return;
}
foreach (Adorner adorner in adorners)
{
if (adorner is WatermarkAdorner)
{
adorner.Visibility = Visibility.Hidden;
layer.Remove(adorner);
}
}
}
}
/// <summary>
/// Show the watermark on the specified control
/// </summary>
/// <param name="control">Control to show the watermark on</param>
private static void ShowWatermark(Control control)
{
AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);
// layer could be null if control is no longer in the visual tree
if (layer != null)
{
layer.Add(new WatermarkAdorner(control, GetWatermark(control)));
}
}
/// <summary>
/// Indicates whether or not the watermark should be shown on the specified control
/// </summary>
/// <param name="c"><see cref="Control"/> to test</param>
/// <returns>true if the watermark should be shown; false otherwise</returns>
private static bool ShouldShowWatermark(Control c)
{
if (c is ComboBox)
{
return (c as ComboBox).Text == string.Empty;
}
else if (c is TextBoxBase)
{
return (c as TextBox).Text == string.Empty;
}
else if (c is ItemsControl)
{
return (c as ItemsControl).Items.Count == 0;
}
else
{
return false;
}
}
#endregion
}
附加属性使用一个名为 WatermarkAdorner
的类,这是源代码:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
/// <summary>
/// Adorner for the watermark
/// </summary>
internal class WatermarkAdorner : Adorner
{
#region Private Fields
/// <summary>
/// <see cref="ContentPresenter"/> that holds the watermark
/// </summary>
private readonly ContentPresenter contentPresenter;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="WatermarkAdorner"/> class
/// </summary>
/// <param name="adornedElement"><see cref="UIElement"/> to be adorned</param>
/// <param name="watermark">The watermark</param>
public WatermarkAdorner(UIElement adornedElement, object watermark) :
base(adornedElement)
{
this.IsHitTestVisible = false;
this.contentPresenter = new ContentPresenter();
this.contentPresenter.Content = watermark;
this.contentPresenter.Opacity = 0.5;
this.contentPresenter.Margin = new Thickness(Control.Margin.Left + Control.Padding.Left, Control.Margin.Top + Control.Padding.Top, 0, 0);
if (this.Control is ItemsControl && !(this.Control is ComboBox))
{
this.contentPresenter.VerticalAlignment = VerticalAlignment.Center;
this.contentPresenter.HorizontalAlignment = HorizontalAlignment.Center;
}
// Hide the control adorner when the adorned element is hidden
Binding binding = new Binding("IsVisible");
binding.Source = adornedElement;
binding.Converter = new BooleanToVisibilityConverter();
this.SetBinding(VisibilityProperty, binding);
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the number of children for the <see cref="ContainerVisual"/>.
/// </summary>
protected override int VisualChildrenCount
{
get { return 1; }
}
#endregion
#region Private Properties
/// <summary>
/// Gets the control that is being adorned
/// </summary>
private Control Control
{
get { return (Control)this.AdornedElement; }
}
#endregion
#region Protected Overrides
/// <summary>
/// Returns a specified child <see cref="Visual"/> for the parent <see cref="ContainerVisual"/>.
/// </summary>
/// <param name="index">A 32-bit signed integer that represents the index value of the child <see cref="Visual"/>. The value of index must be between 0 and <see cref="VisualChildrenCount"/> - 1.</param>
/// <returns>The child <see cref="Visual"/>.</returns>
protected override Visual GetVisualChild(int index)
{
return this.contentPresenter;
}
/// <summary>
/// Implements any custom measuring behavior for the adorner.
/// </summary>
/// <param name="constraint">A size to constrain the adorner to.</param>
/// <returns>A <see cref="Size"/> object representing the amount of layout space needed by the adorner.</returns>
protected override Size MeasureOverride(Size constraint)
{
// Here's the secret to getting the adorner to cover the whole control
this.contentPresenter.Measure(Control.RenderSize);
return Control.RenderSize;
}
/// <summary>
/// When overridden in a derived class, positions child elements and determines a size for a <see cref="FrameworkElement"/> derived class.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
this.contentPresenter.Arrange(new Rect(finalSize));
return finalSize;
}
#endregion
}
现在您可以像这样在任何 TextBox 上放置水印:
<AdornerDecorator>
<TextBox x:Name="SearchTextBox">
<controls:WatermarkService.Watermark>
<TextBlock>Type here to search text</TextBlock>
</controls:WatermarkService.Watermark>
</TextBox>
</AdornerDecorator>
水印可以是您想要的任何内容(文本、图像...)。除了适用于 TextBoxes,此水印还适用于 ComboBoxes 和 ItemControls。
此代码改编自this blog post .
关于c# - TextBox 中的水印/提示/占位符文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/833943/
我的 friend 编写了一个程序,它比较随机排列的骰子面,以找到分布最均匀的面——尤其是当面不仅仅是序列时。 我将他的程序翻译成 haskell 是因为我一直在寻找一个理由来让别人知道 haskel
我需要对表单中的某些字段进行评论/提示。我的想法是在模型中描述它,就像attributeLabels一样。我该怎么做? 然后它会是理想的,如果 Gii 模型(和 Crud)生成器直接从 mysql 列
我们使用 FastReport 来生成报告。事实上,我们为访问源代码付费。 我们目前使用的是 FastReport 的最新稳定版本。虽然它对于我们的生产来说足够稳定,但每当我编译时,我都会看到以下内容
我需要创建一个对话框/提示,包括用于用户输入的文本框。我的问题是,确认对话框后如何获取文本?通常我会为此创建一个类,将文本保存在属性中。不过我想使用 XAML 设计对话框。因此,我必须以某种方式扩展
我想提示用户是否要执行操作(删除) - 用警报框说"is"或“否”,如果是,则运行删除脚本,如果否,则不执行任何操作 我不太了解 javascript,因此是否有人可以使用 javascript 获得
所以我正在编写一个简单的 JS 代码。我们刚刚开始学习函数。我需要创建一个名为“printStars”的函数。 我需要从用户那里获取一个号码,并根据该号码打印“*”。 这就是我所做的:
我在我的页面上添加了一个提示,但它在页面加载之前加载了。如何仅在整个页面可见时才显示消息? 这是我的提示: if (name == null || name == "") { txt == "No
我在我的页面上添加了一个提示,但它在页面加载之前加载了。如何仅在整个页面可见时才显示消息? 这是我的提示: if (name == null || name == "") { txt == "No
我正在自定义我的 zsh 提示,并发现以下内容来检查是否有任何后台作业: if [[ $(jobs | wc -l) -gt 0 ]]; then # has background job(s)
这个问题在这里已经有了答案: JavaScript object: access variable property by name as string [duplicate] (3 个答案) pa
我正在尝试用 javascript 制作一个简单的数学练习程序。在提示警报中给出不同的值,并将答案与用户输入进行比较。这是代码: Calculations generate(); functio
在这段代码中,尽管我使用了文本对齐属性在“编辑文本” View 的中心设置“提示”。但它无法正常工作。 最佳答案 尝试 关于android - 如何在编辑文本的中心对齐文本(提示),我们在Sta
我正在尝试让我的 EditText 显示一个提示,例如“请在此处输入答案”,当用户点击 EditText 以键入他们的答案时,文本应该消失并留空,以便他们在其中输入答案. 截至目前,这就是我的 .xm
我当前的 android 应用程序中有两个微调器,我想要一个默认值,例如 editText 的 android:hint 功能。有没有办法这样做,但不会将提示添加到填充微调器的字符串数组。例如从微调器
如果我的表单已完全填写,我如何提示“感谢您填写表单,“name”!” function submit_onclick() { if(confirm("Thanks for completing t
我刚刚了解了prompt()命令;我知道 Prompt() 命令以字符串的形式返回用户输入。我正在搞乱下面的程序,我输入了Per“Dead”Ohlin作为男性名字。为什么这有效并且没有引起任何问题?
void openUpNow(FILE *x, FILE *y) { x = fopen("xwhatever", "r"); y = fopen("ywhatever", "r");
我有一个作业正在处理,但我在使用 prompt() 方法时遇到了问题。我看到我可以做一个提示,但我需要几个并且有数量。 例如... 我创建了一个 HTML 表格,其中包含许多艺术家和包含 DVD、CD
我正在学习 Big Nerd Ranch 的 iOS Programming, 2nd Edition,我已经来到第 4 章挑战:标题。该练习暗示我感到困惑;它说我需要做一些我认为不需要做的事情。 到
抱歉,如果这是微不足道的,但我没有找到任何解决此问题的建议。我在 Ubuntu 上,我的 Yii 项目需要 PHPUnit。我已经安装了 PHPUnit 两次,方法是下载 phpunit.phar 并
我是一名优秀的程序员,十分优秀!