TextBox with hints - csharp
Embed
You can embed this paste into a blog or website with this code:
<iframe class="codetidy" type="text/html" width="100%" src="http://codetidy.com/paste/embed/1674" frameborder="0"></iframe>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication2

{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
: Window

{
public MainWindow
()
{
InitializeComponent
();
Observable
.FromEventPattern(textBox,
"TextChanged").Throttle(TimeSpan
.FromMilliseconds(500)).ObserveOnDispatcher().Subscribe(OnTextChanged
);
}
public void OnTextChanged
(EventPattern
<EventArgs
> eventPatternArgs
)
{
var textBox
= eventPatternArgs
.Sender as TextBox
;
if(textBox
!= null)
{
var adornerLayer
= AdornerLayer
.GetAdornerLayer(textBox
);
textBoxHintAdorner
= new TextBoxHintAdorner
(textBox
);
adornerLayer
.Add(textBoxHintAdorner
);
}
disposable
= Observable
.FromEventPattern(textBox,
"TextChanged").ObserveOnDispatcher().Subscribe(OnRemoveAdorner
);
}
public void OnRemoveAdorner
(EventPattern
<EventArgs
> eventPatternArgs
)
{
var textBox
= eventPatternArgs
.Sender as TextBox
;
if (textBox
!= null)
{
var adornerLayer
= AdornerLayer
.GetAdornerLayer(textBox
);
if (textBoxHintAdorner
!= null)
adornerLayer
.Remove(textBoxHintAdorner
);
}
disposable
.Dispose();
}
private IDisposable disposable
;
private TextBoxHintAdorner textBoxHintAdorner
;
}
public class TextBoxHintAdorner
: Adorner

{
public TextBoxHintAdorner
(UIElement adornedElement
) : base(adornedElement
)
{
}
protected override void OnRender
(DrawingContext drawingContext
)
{
var textBox
= AdornedElement
as TextBox
;
if(textBox
== null)
return;
String hintText
= TextHint
.GetHint(textBox
.Text);
var formattedText
= new FormattedText
(hintText, CultureInfo
.GetCultureInfo("en-us"), FlowDirection
.LeftToRight,
new Typeface
("Verdana"),
10, Brushes
.Black);
Rect rect
= textBox
.GetRectFromCharacterIndex(textBox
.Text.Length);
drawingContext
.DrawRectangle(Brushes
.Yellow,
null,
new Rect
(rect
.TopRight.X + 10, rect
.TopRight.Y, formattedText
.Width, formattedText
.Height));
drawingContext
.DrawText(formattedText,
new Point
(rect
.BottomRight.X + 10,
0));
}
}
public class TextHint

{
public static String GetHint
(String text
)
{
int words
= text
.Split(new char[] {' '}).Count();
if(words
== 1)
return "circle|polygon";
if (words
== 2)
return "<n> sides";
if (words
== 4)
return "<x> colour";
return string.Empty;
}
}
}