9 public static class StringFormatHelper
13 public static DependencyProperty ValueProperty = DependencyProperty.RegisterAttached(
"Value", typeof(
object), typeof(StringFormatHelper),
new PropertyMetadata(
null, OnValueChanged));
15 private static void OnValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
17 RefreshFormattedValue(obj);
20 public static object GetValue(DependencyObject obj)
22 return obj.GetValue(ValueProperty);
25 public static void SetValue(DependencyObject obj,
object newValue)
27 obj.SetValue(ValueProperty, newValue);
34 public static DependencyProperty FormatProperty = DependencyProperty.RegisterAttached(
"Format", typeof(
string), typeof(StringFormatHelper),
new PropertyMetadata(
null, OnFormatChanged));
36 private static void OnFormatChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
38 RefreshFormattedValue(obj);
41 public static string GetFormat(DependencyObject obj)
43 return (
string)obj.GetValue(FormatProperty);
46 public static void SetFormat(DependencyObject obj,
string newFormat)
48 obj.SetValue(FormatProperty, newFormat);
53 #region FormattedValue
55 public static DependencyProperty FormattedValueProperty = DependencyProperty.RegisterAttached(
"FormattedValue", typeof(
string), typeof(StringFormatHelper),
new PropertyMetadata(
null));
57 public static string GetFormattedValue(DependencyObject obj)
59 return (
string)obj.GetValue(FormattedValueProperty);
62 public static void SetFormattedValue(DependencyObject obj,
string newFormattedValue)
64 obj.SetValue(FormattedValueProperty, newFormattedValue);
69 private static void RefreshFormattedValue(DependencyObject obj)
71 object value = GetValue(obj);
72 string format = GetFormat(obj);
76 if (!format.StartsWith(
"{0:"))
78 format = String.Format(
"{{0:{0}}}", format);
81 SetFormattedValue(obj, String.Format(format, value));
85 SetFormattedValue(obj, value ==
null ? String.Empty : value.ToString());