Style定义实例

给Textbox定义一个阴影效果。

  1. <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
  2. <Setter Property="SnapsToDevicePixels" Value="True"/>
  3. <Setter Property="OverridesDefaultStyle" Value="True"/>
  4. <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
  5. <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
  6. <Setter Property="MinWidth" Value="120"/>
  7. <Setter Property="MinHeight" Value="20"/>
  8. <Setter Property="AllowDrop" Value="true"/>
  9. <Setter Property="Template">
  10. <Setter.Value>
  11. <ControlTemplate TargetType="{x:Type TextBoxBase}">
  12. <Border x:Name="Border"
  13. BorderThickness="1"
  14. CornerRadius="2"
  15. Padding="0">
  16. <Border.BorderBrush>
  17. <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
  18. <GradientStop Color="#888888" Offset="0" />
  19. <GradientStop Color="#AAAAAA" Offset=".2" />
  20. </LinearGradientBrush>
  21. </Border.BorderBrush>
  22. <ScrollViewer x:Name="PART_ContentHost" Margin="0">
  23. <ScrollViewer.Background>
  24. <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
  25. <GradientStop Offset="0" Color="WhiteSmoke"/>
  26. <GradientStop Offset="1" Color="LightGray"/>
  27. </LinearGradientBrush>
  28. </ScrollViewer.Background>
  29. </ScrollViewer>
  30. </Border>
  31.  
  32. <ControlTemplate.Triggers>
  33. <Trigger Property="IsEnabled" Value="False">
  34. <Setter TargetName="Border" Property="Background" Value="#EEEEEE"/>
  35. <Setter TargetName="Border" Property="BorderBrush" Value="#EEEEEE"/>
  36. <Setter Property="Foreground" Value="#888888"/>
  37. </Trigger>
  38. </ControlTemplate.Triggers>
  39. </ControlTemplate>
  40. </Setter.Value>
  41. </Setter>
  42. </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
  1. <Binding Path="UpperLeftCornerLatitude" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Delay="1000">
  2. </Binding>
  1. //NumericTextBoxBehavior
  2. /// <summary>
  3. /// This forces a TextBoxBase control to be numeric-entry only
  4. /// </summary>
  5. /// <example>
  6. /// <![CDATA[ <TextBox Cinch:NumericTextBoxBehavior.IsEnabled="True" /> ]]>
  7. /// </example>
  8. public static class NumericTextBoxBehavior
  9. {
  10. #region IsEnabled DP
  11. /// <summary>
  12. /// Dependency Property for turning on numeric behavior in a TextBox.
  13. /// </summary>
  14. public static readonly DependencyProperty IsEnabledProperty =
  15. DependencyProperty.RegisterAttached("IsEnabled",
  16. typeof(bool), typeof(NumericTextBoxBehavior),
  17. new UIPropertyMetadata(false, OnEnabledStateChanged));
  18.  
  19. /// <summary>
  20. /// Attached Property getter for the IsEnabled property.
  21. /// </summary>
  22. /// <param name="source">Dependency Object</param>
  23. /// <returns>Current property value</returns>
  24. public static bool GetIsEnabled(DependencyObject source)
  25. {
  26. return (bool)source.GetValue(IsEnabledProperty);
  27. }
  28.  
  29. /// <summary>
  30. /// Attached Property setter for the IsEnabled property.
  31. /// </summary>
  32. /// <param name="source">Dependency Object</param>
  33. /// <param name="value">Value to set on the object</param>
  34. public static void SetIsEnabled(DependencyObject source, bool value)
  35. {
  36. source.SetValue(IsEnabledProperty, value);
  37. }
  38.  
  39. /// <summary>
  40. /// This is the property changed handler for the IsEnabled property.
  41. /// </summary>
  42. /// <param name="sender"></param>
  43. /// <param name="e"></param>
  44. private static void OnEnabledStateChanged(DependencyObject sender,
  45. DependencyPropertyChangedEventArgs e)
  46. {
  47. TextBox tb = sender as TextBox;
  48. if (tb == null)
  49. return;
  50.  
  51. tb.PreviewTextInput -= tbb_PreviewTextInput;
  52. DataObject.RemovePastingHandler(tb, OnClipboardPaste);
  53.  
  54. bool b = ((e.NewValue != null && e.NewValue.GetType() == typeof(bool))) ?
  55. (bool)e.NewValue : false;
  56. if (b)
  57. {
  58. tb.PreviewTextInput += tbb_PreviewTextInput;
  59. DataObject.AddPastingHandler(tb, OnClipboardPaste);
  60. }
  61. }
  62.  
  63. #endregion
  64.  
  65. #region Private Methods
  66.  
  67. /// <summary>
  68. /// This method handles paste and drag/drop events
  69. /// onto the TextBox. It restricts the character
  70. /// set to numerics and ensures we have consistent behavior.
  71. /// </summary>
  72. /// <param name="sender">TextBox sender</param>
  73. /// <param name="e">EventArgs</param>
  74. private static void OnClipboardPaste(object sender, DataObjectPastingEventArgs e)
  75. {
  76. TextBox tb = sender as TextBox;
  77. string text = e.SourceDataObject.GetData(e.FormatToApply) as string;
  78.  
  79. if (tb != null && !string.IsNullOrEmpty(text) && !Validate(tb, text))
  80. e.CancelCommand();
  81. }
  82.  
  83. /// <summary>
  84. /// This checks if the resulting string will match the regex expression
  85. /// </summary>
  86. static void tbb_PreviewTextInput(object sender, TextCompositionEventArgs e)
  87. {
  88. TextBox tb = sender as TextBox;
  89.  
  90. if (tb != null && !Validate(tb, e.Text))
  91. e.Handled = true;
  92. }
  93.  
  94. #endregion
  95.  
  96. private static bool Validate(TextBox tb, string newContent)
  97. {
  98. string testString = string.Empty;
  99. // replace selection with new text.
  100. if (!string.IsNullOrEmpty(tb.SelectedText))
  101. {
  102. string pre = tb.Text.Substring(0, tb.SelectionStart);
  103. string after = tb.Text.Substring(tb.SelectionStart + tb.SelectionLength,
  104. tb.Text.Length - (tb.SelectionStart + tb.SelectionLength));
  105. testString = pre + newContent + after;
  106. }
  107. else
  108. {
  109. string pre = tb.Text.Substring(0, tb.CaretIndex);
  110. string after = tb.Text.Substring(tb.CaretIndex,
  111. tb.Text.Length - tb.CaretIndex);
  112. testString = pre + newContent + after;
  113. }
  114.  
  115. Regex regExpr = new Regex(@"^([-+]?)(\d*)([,.]?)(\d*)$");
  116. if (regExpr.IsMatch(testString))
  117. return true;
  118.  
  119. return false;
  120. }
  121. }

WaterMark/HintText/PlaceHoder

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

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

  1. <!--Add a placeHolder for TextBox using Tag value-->
  2. <Style x:Key="placeHolder" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
  3. <Setter Property="Template">
  4. <Setter.Value>
  5. <ControlTemplate TargetType="{x:Type TextBox}">
  6. <Grid>
  7. <TextBox Text="{Binding Path=Text,
  8. RelativeSource={RelativeSource TemplatedParent},
  9. Mode=TwoWay,
  10. UpdateSourceTrigger=PropertyChanged,
  11. Delay=1000}"
  12. x:Name="textSource"
  13. Background="Transparent"
  14. Panel.ZIndex="2" />
  15. <TextBox Text="{TemplateBinding Tag}" Background="{TemplateBinding Background}" Panel.ZIndex="1">
  16. <TextBox.Style>
  17. <Style TargetType="{x:Type TextBox}">
  18. <Setter Property="Foreground" Value="Transparent" />
  19. <Style.Triggers>
  20. <DataTrigger Binding="{Binding Path=Text, Source={x:Reference textSource}}" Value="">
  21. <Setter Property="Foreground" Value="LightGray" />
  22. </DataTrigger>
  23. </Style.Triggers>
  24. </Style>
  25. </TextBox.Style>
  26. </TextBox>
  27. </Grid>
  28. </ControlTemplate>
  29. </Setter.Value>
  30. </Setter>
  31. </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. .NET 扩展方法 (一)

    我还记得刚刚学编程的时候,老师经常会提到一句话:注意空指针.所以经常在某些“入口”位置,进行代码校验,空指针的判断就是其中的一项工作. string类型作为常用的数据类型,它在项目中出现的机率极高,所 ...

  2. Java中从键盘中任意输入字符串,将其转换成数字后,并求和

  3. 容器--TreeMap

    一.概述 在Map的实现中,除了我们最常见的KEY值无序的HashMap之外,还有KEY有序的Map,比较常用的有两类,一类是按KEY值的大小有序的Map,这方面的代表是TreeMap,另外一种就保持 ...

  4. Entity Framework Code First 中使用 Fluent API 笔记。

    在做MVC+EF CodeFirst 的Demo时,碰到的问题, 在组册用户时,要让用户输入确认密码,但是数据库中又不需要保存这个字段,解决方案很多了,这里我列出通过EF Code First的解决方 ...

  5. 天津政府应急系统之GIS一张图(arcgis api for flex)讲解(十三)台风模块

    config.xml文件的配置如下: <widget label="台风" icon="assets/images/typhoon.png" config ...

  6. Android Studio 运行出现 Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

    转载请标明出处: http://www.cnblogs.com/why168888/p/5978381.html 本文出自:[Edwin博客园] 我引用compile 'com.squareup.re ...

  7. iOS推送(利用极光推送)

    本文主要是基于极光推送的SDK封装的一个快速集成极光推送的类的封装(不喜勿喷) (1)首先说一下推送的一些原理: Push的原理: Push 的工作机制可以简单的概括为下图 图中,Provider是指 ...

  8. DIY一个高大上带提醒的计时器,简单实用,你还在等什么

    小编心语:锵锵锵!小编我又来了!昨天发了一篇比较实用的<Python聊天室>,鉴于反响还不错,SO ,小编也想给大家多分享点有用的干货,让大家边学边用.好了,闲话不多说,今天要给各位看官们 ...

  9. jQuery与Zepto的异同

    一,同: Zepto最初是为移动端开发的库,是jQuery的轻量级替代品,因为它的API和jQuery相似,而文件更小.Zepto最大的优势是它的文件大小,只有8k多,是目前功能完备的库中最小的一个, ...

  10. 高性能Linux服务器构建实战笔记

    一.            web应用篇 1           HTTP服务器Nginx 1.1          性能上.功能上.安装上与Apache对比 l  性能上占用系统资源少,支持并发高 ...