change textblock background color when text equal to referenceValue
cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace MCE.Gems.Common.Controls.CustomControls { /// <summary> /// change textblock background color when text equal to referenceValue /// </summary> public class MyTextBlock : TextBlock { #region DependencyProperty public string ReferenceValue { get { return (string)GetValue(ReferenceValueProperty); } set { SetValue(ReferenceValueProperty, value); } } // Using a DependencyProperty as the backing store for ReferenceValue. This enables animation, styling, binding, etc... public static readonly DependencyProperty ReferenceValueProperty = DependencyProperty.Register("ReferenceValue", typeof(string), typeof(MyTextBlock), new PropertyMetadata(null, new PropertyChangedCallback(OnReferenceValueChanged))); private static void OnReferenceValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MyTextBlock mb = d as MyTextBlock; if (mb.DisplayText!=null) { if (mb.DisplayText.ToString().Equals(e.NewValue.ToString())) { mb.Background = mb.EqualBackground; } } } public string DisplayText { get { return (string)GetValue(DisplayTextProperty); } set { SetValue(DisplayTextProperty, value); } } // Using a DependencyProperty as the backing store for DisplayText. This enables animation, styling, binding, etc... public static readonly DependencyProperty DisplayTextProperty = DependencyProperty.Register("DisplayText", typeof(string), typeof(MyTextBlock), new PropertyMetadata(null, new PropertyChangedCallback(OnDisplayTextChanged))); private static void OnDisplayTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MyTextBlock mb = d as MyTextBlock; mb.Text = e.NewValue.ToString(); if (mb.ReferenceValue!=null) { if (mb.ReferenceValue.ToString().Equals(e.NewValue.ToString())) { mb.Background = mb.EqualBackground; } } } public Brush EqualBackground { get { return (Brush)GetValue(EqualBackgroundProperty); } set { SetValue(EqualBackgroundProperty, value); } } // Using a DependencyProperty as the backing store for EqualBackground. This enables animation, styling, binding, etc... public static readonly DependencyProperty EqualBackgroundProperty = DependencyProperty.Register("EqualBackground", typeof(Brush), typeof(MyTextBlock), new PropertyMetadata(null, new PropertyChangedCallback(OnEqualBackgroundChanged))); private static void OnEqualBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MyTextBlock mb = d as MyTextBlock; if (mb.ReferenceValue != null&&mb.DisplayText!=null) { if (mb.ReferenceValue.ToString().Equals(mb.DisplayText.ToString())) { mb.Background = e.NewValue as Brush; } } } #endregion } }