Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Copyright & License: :) The Code is very Trivial. If copyright applicable, then (C) 2015 Bsod64 :D
- *
- * Usage:
- * Add it to your project.
- *
- * In your xaml file first add to the xmlns section something along the lines of:
- * xmlns:customwidgets="clr-namespace:Bsod64.CustomWpfControls"
- * (To change this, simple reflect your change in the namespace of this file.)
- *
- * Then use it in your xaml file:
- * <customwidgets:TextboxWithPlaceholder Placeholder="My placeholder text here" />
- *
- */
- using Microsoft.Win32;
- using System;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media;
- namespace Bsod64.CustomWpfControls
- {
- class TextboxWithPlaceholder: TextBox
- {
- private Brush _placeholderColor = Brushes.Gray;
- public string Placeholder
- {
- get
- {
- return (string)GetValue(PlaceholderProperty);
- }
- set
- {
- SetValue(PlaceholderProperty, value);
- }
- }
- public static readonly DependencyProperty PlaceholderProperty =
- DependencyProperty.Register("Placeholder", typeof(string), typeof(TextboxWithPlaceholder), new PropertyMetadata(default(string)));
- protected void Usability_PropertyChanged(object sender, EventArgs e)
- {
- if(!SystemParameters.HighContrast)
- {
- _placeholderColor = Brushes.Gray;
- if(Text.Equals(Placeholder))
- Foreground = _placeholderColor;
- }
- else
- {
- ClearValue(TextboxWithPlaceholder.ForegroundProperty);
- _placeholderColor = Foreground;
- }
- }
- protected override void OnInitialized(EventArgs e)
- {
- base.OnInitialized(e);
- SystemEvents.UserPreferenceChanged += Usability_PropertyChanged; // Starting .NET 4.5 can you can use SystemParameters.StaticPropertyChanged
- ShowPlaceholder();
- }
- protected override void OnGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e)
- {
- base.OnGotKeyboardFocus(e);
- if(Text.Equals(Placeholder))
- HidePlaceholder();
- }
- protected override void OnLostKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e)
- {
- base.OnLostKeyboardFocus(e);
- if(Text.Equals(String.Empty))
- ShowPlaceholder();
- }
- public void ShowPlaceholder()
- {
- Text = Placeholder;
- Foreground = _placeholderColor;
- FontStyle = FontStyles.Italic;
- }
- public void HidePlaceholder()
- {
- Text = String.Empty;
- ClearValue(TextboxWithPlaceholder.ForegroundProperty);
- FontStyle = FontStyles.Normal;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement