我为此创建了一个附加属性和转换器。您可能已经拥有转换器,因此请将我对 CaseConverter 的引用替换为您拥有的任何实现。
附加属性只是一个布尔值,如果您希望它是大写的(您显然可以将其扩展为可枚举的样式选择)。当属性发生变化时,它会根据需要重新绑定 TextBlock 的 Text 属性,并添加到转换器中。
当属性已经绑定时,可能需要做更多的工作——我的解决方案假设它是一个简单的路径绑定。但它可能还需要复制源等。但是我觉得这个例子足以说明我的观点。
这是附加的属性:
public static bool GetUppercase(DependencyObject obj)
{
return (bool)obj.GetValue(UppercaseProperty);
}
public static void SetUppercase(DependencyObject obj, bool value)
{
obj.SetValue(UppercaseProperty, value);
}
// Using a DependencyProperty as the backing store for Uppercase. This enables animation, styling, binding, etc...
public static readonly DependencyProperty UppercaseProperty =
DependencyProperty.RegisterAttached("Uppercase", typeof(bool), typeof(TextHelper), new PropertyMetadata(false, OnUppercaseChanged));
private static void OnUppercaseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBlock txt = d as TextBlock;
if (txt == null) return;
var val = (bool)e.NewValue;
if (val)
{
// rebind the text using converter
// if already bound, use it as source
var original = txt.GetBindingExpression(TextBlock.TextProperty);
var b = new Binding();
if (original != null)
{
b.Path = original.ParentBinding.Path;
}
else
{
b.Source = txt.Text;
}
b.Converter = new CaseConverter() { Case = CharacterCasing.Upper };
txt.SetBinding(TextBlock.TextProperty, b);
}
}