Style定义实例

给Textbox定义一个阴影效果。

<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="MinWidth" Value="120"/>
<Setter Property="MinHeight" Value="20"/>
<Setter Property="AllowDrop" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border x:Name="Border"
BorderThickness="1"
CornerRadius="2"
Padding="0">
<Border.BorderBrush>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="#888888" Offset="0" />
<GradientStop Color="#AAAAAA" Offset=".2" />
</LinearGradientBrush>
</Border.BorderBrush>
<ScrollViewer x:Name="PART_ContentHost" Margin="0">
<ScrollViewer.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="WhiteSmoke"/>
<GradientStop Offset="1" Color="LightGray"/>
</LinearGradientBrush>
</ScrollViewer.Background>
</ScrollViewer>
</Border> <ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="#EEEEEE"/>
<Setter TargetName="Border" Property="BorderBrush" Value="#EEEEEE"/>
<Setter Property="Foreground" Value="#888888"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

 

UpdateSourceTrigger

 

默认UpdateSourceTrigger为LostFoucs,有时需要及时CommitValue,则需要设置为PropertyChanged。这样当Text属性的值发生变化时,我们的值就能及时更新到Datasource中。

更多参考

How to: Control When the TextBox Text Updates the Source

NumberTextbox

  1. 使用NubmberTextboxBehavior
  2. 将TextBox的binding属性中Delay设置为1000
<Binding Path="UpperLeftCornerLatitude" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Delay="1000">
</Binding>
//NumericTextBoxBehavior
/// <summary>
/// This forces a TextBoxBase control to be numeric-entry only
/// </summary>
/// <example>
/// <![CDATA[ <TextBox Cinch:NumericTextBoxBehavior.IsEnabled="True" /> ]]>
/// </example>
public static class NumericTextBoxBehavior
{
#region IsEnabled DP
/// <summary>
/// Dependency Property for turning on numeric behavior in a TextBox.
/// </summary>
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached("IsEnabled",
typeof(bool), typeof(NumericTextBoxBehavior),
new UIPropertyMetadata(false, OnEnabledStateChanged)); /// <summary>
/// Attached Property getter for the IsEnabled property.
/// </summary>
/// <param name="source">Dependency Object</param>
/// <returns>Current property value</returns>
public static bool GetIsEnabled(DependencyObject source)
{
return (bool)source.GetValue(IsEnabledProperty);
} /// <summary>
/// Attached Property setter for the IsEnabled property.
/// </summary>
/// <param name="source">Dependency Object</param>
/// <param name="value">Value to set on the object</param>
public static void SetIsEnabled(DependencyObject source, bool value)
{
source.SetValue(IsEnabledProperty, value);
} /// <summary>
/// This is the property changed handler for the IsEnabled property.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnEnabledStateChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb == null)
return; tb.PreviewTextInput -= tbb_PreviewTextInput;
DataObject.RemovePastingHandler(tb, OnClipboardPaste); bool b = ((e.NewValue != null && e.NewValue.GetType() == typeof(bool))) ?
(bool)e.NewValue : false;
if (b)
{
tb.PreviewTextInput += tbb_PreviewTextInput;
DataObject.AddPastingHandler(tb, OnClipboardPaste);
}
} #endregion #region Private Methods /// <summary>
/// This method handles paste and drag/drop events
/// onto the TextBox. It restricts the character
/// set to numerics and ensures we have consistent behavior.
/// </summary>
/// <param name="sender">TextBox sender</param>
/// <param name="e">EventArgs</param>
private static void OnClipboardPaste(object sender, DataObjectPastingEventArgs e)
{
TextBox tb = sender as TextBox;
string text = e.SourceDataObject.GetData(e.FormatToApply) as string; if (tb != null && !string.IsNullOrEmpty(text) && !Validate(tb, text))
e.CancelCommand();
} /// <summary>
/// This checks if the resulting string will match the regex expression
/// </summary>
static void tbb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox tb = sender as TextBox; if (tb != null && !Validate(tb, e.Text))
e.Handled = true;
} #endregion private static bool Validate(TextBox tb, string newContent)
{
string testString = string.Empty;
// replace selection with new text.
if (!string.IsNullOrEmpty(tb.SelectedText))
{
string pre = tb.Text.Substring(0, tb.SelectionStart);
string after = tb.Text.Substring(tb.SelectionStart + tb.SelectionLength,
tb.Text.Length - (tb.SelectionStart + tb.SelectionLength));
testString = pre + newContent + after;
}
else
{
string pre = tb.Text.Substring(0, tb.CaretIndex);
string after = tb.Text.Substring(tb.CaretIndex,
tb.Text.Length - tb.CaretIndex);
testString = pre + newContent + after;
} Regex regExpr = new Regex(@"^([-+]?)(\d*)([,.]?)(\d*)$");
if (regExpr.IsMatch(testString))
return true; return false;
}
}

WaterMark/HintText/PlaceHoder

  1. 通过Style
  2. 通过AttachBehavior
  3. 通过自定义控件

1.给TextBox添加水印效果(提示文字)

<!--Add a placeHolder for TextBox using Tag value-->
<Style x:Key="placeHolder" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Grid>
<TextBox Text="{Binding Path=Text,
RelativeSource={RelativeSource TemplatedParent},
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
Delay=1000}"
x:Name="textSource"
Background="Transparent"
Panel.ZIndex="2" />
<TextBox Text="{TemplateBinding Tag}" Background="{TemplateBinding Background}" Panel.ZIndex="1">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Text, Source={x:Reference textSource}}" Value="">
<Setter Property="Foreground" Value="LightGray" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

2.通过AttachBehavior

 

3.通过自定义控件

 

 

参考

WPF validation rule preventing decimal entry in textbox?

Set WPF Binding.StringFormat Property on TextBox via Style

【WPF系列】Textbox的更多相关文章

  1. [WPF系列]-数据邦定之DataTemplate 对分层数据的支持

    到目前为止,我们仅讨论如何绑定和显示单个集合. 某些时候,您要绑定的集合包含其他集合. HierarchicalDataTemplate 类专用于 HeaderedItemsControl 类型以显示 ...

  2. [WPF系列]-数据邦定之DataTemplate 根据对象属性切换模板

      引言 书接上回[WPF系列-数据邦定之DataTemplate],本篇介绍如何根据属性切换模板(DataTemplate)   切换模板的两种方式:   使用DataTemplateSelecto ...

  3. [WPF系列]-DataBinding(数据绑定) 自定义Binding

    自定义Binding A base class for custom WPF binding markup extensions BindingDecoratorBase Code: public c ...

  4. [WPF系列]-TreeView的常用事项

    引言 项目经常会用Treeview来组织一些具有层级结构的数据,本节就将项目使用Treeview常见的问题作一个总结. DataBinding数据绑定 DataTemplate自定义 <Hier ...

  5. [WPF系列]从基础起步学习系列计划

    引言 WPF技术已经算不什么新技术,一搜一大把关于WPF基础甚至高级的内容.之前工作中一直使用winform所以一直没有深入学习WPF,这次因项目中使用了WPF技术来实现比较酷的展示界面.我在这里只是 ...

  6. Wpf解决TextBox文件拖入问题、拖放问题

    在WPF中,当我们尝试向TextBox中拖放文件,从而获取其路径时,往往无法成功(拖放文字可以成功).造成这种原因关键是WPF的TextBox对拖放事件处理机制的不同, 解放方法如下: 使用Previ ...

  7. WPF中TextBox文件拖放问题

    在WPF中,当我们尝试向TextBox中拖放文件,从而获取其路径时,往往无法成功(拖放文字可以成功).造成这种原因关键是WPF的TextBox对拖放事件处理机制的不同,具体可参考这篇文章Textbox ...

  8. WPF 设置TextBox为空时,背景为文字提示

    WPF 设置TextBox为空时,背景为文字提示.   <TextBox FontSize="17" Height="26" Margin="2 ...

  9. WPF 在TextBox失去焦点时检测数据,出错重新获得焦点解决办法

    WPF 在TextBox失去焦点时检测数据,出错重新获得焦点解决办法 在WPF的TextBox的LostFocus事件中直接使用Focus()方法会出现死循环的问题 正确的使用方式有2中方法: 方法一 ...

  10. WPF系列教程——(三)使用Win10 Edge浏览器内核 - 简书

    原文:WPF系列教程--(三)使用Win10 Edge浏览器内核 - 简书 在需要显示一些 H5网站的时候自带的WebBrowser总是显示不了,WebBrowser使用的是IE内核,许多H5新特性都 ...

随机推荐

  1. 4.DB Initialization(数据库初始化)[EF Code-First系列]

    前面的例子中,我们已经看到了Code-First自动为我们创建数据库的例子. 这里我们将要学习的是,当初始化的时候,Code-First是怎么决定数据库的名字和服务的呢??? 下面的图,解释了这一切! ...

  2. 公司的一个面试题:如何用css让一个容器水平垂直居中?

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  3. 利用SHELL脚本实现文件完整性检测程序(1.2版更新)

    一..开发背景 因时势所逼,需要对服务器的文件系统实行监控.虽然linux下有不少入侵检测和防窜改系统,但都比较麻烦,用起来也不是很称手.自己琢磨着也不需要什么多复杂的功能,写个脚本应该就可以满足基本 ...

  4. Ajax制作智能提示搜索

    一.效果图: 二.实现过程: 思路: 三.部分代码: html: <div id="searchbox"> <div><input type=&quo ...

  5. Laravel安装方法 (windows)

    Laravel安装方法(windows) 安装PHP 下载PHP7 http://windows.php.net/download#php-7.0 进入上述网站下载PHP7 选择zip包解压安装 配置 ...

  6. php实现设计模式之 解释器模式

    <?php /* * 解释器模式:给定一种语言,定义它文法的一种表示,并定义一个解释器,该解释器利用该表示来解释语言中的句子 * */ class Expression { function i ...

  7. 时钟周期,CPU周期,指令周期,CPU时间片

    从小到大来说:时钟周期,CPU周期,指令周期,CPU时间片 时钟周期:一个脉冲需要的时间,频率的倒数 CPU周期:读取一个指令节所需的时间 指令周期:读取并执行完一个指令所需的时间 CPU时间片:CP ...

  8. JMeter专题系列(四)参数化

    JMeter也有像LR中的参数化,本篇就来介绍下JMeter的参数化如何去实现. 参数化:录制脚本中有登录操作,需要输入用户名和密码,假如系统不允许相同的用户名和密码同时登录,或者想更好的模拟多个用户 ...

  9. 使用Spring Boot来加速Java web项目的开发

    我想,现在企业级的Java web项目应该或多或少都会使用到Spring框架的. 回首我们以前使用Spring框架的时候,我们需要首先在(如果你使用Maven的话)pom文件中增加对相关的的依赖(使用 ...

  10. 【requireJS路径加载】与程序员小卡的交流

    这两天正好看到了程序员小卡同学的一篇博客,里面对requireJS路径的解析做了一些说明,里面有点问题待解决,我这里正好知道一点,所以整理成文,不知对小卡同学是否有帮助. http://www.cnb ...