我正在尝试创建某种带有发光背景的标签。为此,我决定在内容控件上使用样式。发光效果来自两个DropShadowEffects
,我希望将其绑定到Foreground Property
内容控件的 。Foreground Property
is 类型Brush
和DropShadowEffect.Color
is 类型Color
,所以我需要在这两者之间进行转换。
每当我尝试通过转换器设置发光颜色时,发光效果都会保持黑色。似乎转换器代码甚至从未通过。我确实在转换器中返回了预定义的颜色(无转换),甚至添加了 Debug.Break(),但无济于事。
你能告诉我我做错了什么,或者是否有替代的,可能更好的方法来实现带有发光背景的标签。
转换器:
public class ColorToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
if (value is Color)
{
Color color = (Color)value;
BrushConverter bc = new BrushConverter();
return bc.ConvertFrom(color);
}
Type type = value.GetType();
throw new InvalidOperationException("Unsupported type ["+type.Name+"]");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if (value is Brush)
{
Brush brush = (Brush)value;
BrushConverter bc = new BrushConverter();
return bc.ConvertTo(brush, typeof(Color));
}
Type type = value.GetType();
throw new InvalidOperationException("Unsupported type ["+type.Name+"]");
}
}
在资源字典中:
<local:ColorToBrushConverter x:Key="Color2BrushConverter" />
<Style x:Key="ContentControlGlowStyle" TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Border>
<Border.Effect>
<DropShadowEffect
BlurRadius="15"
Color="{Binding Path=Foreground, Converter={StaticResource Color2BrushConverter}}"
ShadowDepth="2"
Direction="0"/>
</Border.Effect>
<TextBlock Name="Highlight" Foreground="{TemplateBinding Foreground}" Text="{TemplateBinding Content}" Margin="10,5,0,0">
<TextBlock.Effect>
<DropShadowEffect
BlurRadius="15"
Color="{Binding Path=Foreground,Converter={StaticResource Color2BrushConverter}}"
ShadowDepth="2"
Direction="0"/>
</TextBlock.Effect>
</TextBlock>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
在 XAML 中:
<ContentControl Name="cc2" Style="{DynamicResource ContentControlGlowStyle}"
FontSize="24"
Foreground="LightBlue"
Background="LightBlue"
Content="some content to display"
FontFamily="Verdana" />