在运行时根据枚举值更改边界背景



我正在设计一个自定义控件,我希望用户能够使用自定义属性更改背景颜色。背景颜色应由名为Severity:的枚举指定

代码

public enum Severity
{
Warning,
Information,
Success,
Error
}

Xaml

<Border Background="{DynamicResource InfoBarInformationalSeverityBackgroundBrush}" 
CornerRadius="4">
<Grid Margin="10">
<TextBlock Text="{Binding Title, 
RelativeSource={RelativeSource AncestorType=ib:InfoBar}}"/>
</Grid>
</Border>
<InfoBar Severity="Error"/>

我试了一下扳机,但似乎不起作用

更新:

Xaml

<Border>
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding Severity, 
RelativeSource={RelativeSource AncestorType=ib:InfoBar}}" 
Value="Error">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
<DataTrigger Binding="{Binding Severity, 
RelativeSource={RelativeSource AncestorType=ib:InfoBar}}" 
Value="Success">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>

代码

public Severity Severity
{
get { return (Severity) GetValue(SeverityProperty); }
set { SetValue(SeverityProperty, value); }
}

public static readonly DependencyProperty SeverityProperty =
DependencyProperty.Register("Severity", typeof(Brushes), typeof(InfoBar));

您可以使用转换器。传递您的枚举并转换为一种颜色:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Color colorDefalut = (Color)ColorConverter.ConvertFromString("#00afef");
switch ((int)value)
{
case (int) Severity. Warning:
return new SolidColorBrush(Colors.Yellow);
case (int) Severity.Information:
return new SolidColorBrush(Colors.bleu);
case (int) Severity. Error:

return new SolidColorBrush(colors.Red);
default:
return new SolidColorBrush(colorDefalut);
}
}

依赖属性应注册为Severity,而不是Brushes:

public static readonly DependencyProperty SeverityProperty =
DependencyProperty.Register(nameof(Severity), typeof(Severity), typeof(InfoBar));

然后,假设BorderInfoBar控件的可视子控件,则您的示例应该有效:

<b:InfoBar Severity="Warning">
<Border>
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<DataTrigger Binding="{Binding Severity, RelativeSource={RelativeSource AncestorType=b:InfoBar}}" Value="Warning">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
<DataTrigger Binding="{Binding Severity, RelativeSource={RelativeSource AncestorType=b:InfoBar}}" Value="Success">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding Severity, RelativeSource={RelativeSource AncestorType=b:InfoBar}}" />
</Border>
</StackPanel>
</b:InfoBar>

最新更新