C# 在运行时基于枚举值更改边框背景
我正在设计一个自定义控件,我希望用户能够使用自定义属性更改背景颜色。 背景颜色应由称为严重性的枚举指定: 代码C# 在运行时基于枚举值更改边框背景,c#,wpf,triggers,C#,Wpf,Triggers,我正在设计一个自定义控件,我希望用户能够使用自定义属性更改背景颜色。 背景颜色应由称为严重性的枚举指定: 代码 公共枚举严重性 { 警告 信息 成功 错误 } Xaml 我试过扳机,但似乎不起作用 更新: Xaml 代码 公共严重性 { 获取{return(Severity)GetValue(SeverityProperty);} set{SetValue(SeverityProperty,value);} } 公共静态只读从属属性SeverityProperty= Dependenc
公共枚举严重性
{
警告
信息
成功
错误
}
Xaml
我试过扳机,但似乎不起作用
更新:
Xaml
代码
公共严重性
{
获取{return(Severity)GetValue(SeverityProperty);}
set{SetValue(SeverityProperty,value);}
}
公共静态只读从属属性SeverityProperty=
DependencyProperty.Register(“严重性”、类型(画笔)、类型(信息栏));
依赖项属性应注册为严重性
,而不是刷子
:
public static readonly DependencyProperty SeverityProperty =
DependencyProperty.Register(nameof(Severity), typeof(Severity), typeof(InfoBar));
然后,假设边框
是信息栏
控件的可视子控件,您的示例应该可以工作:
<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>
您可以使用转换器。将枚举和转换传递到颜色:
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 of type Severity?Register(“Severity”,typeof(Bruses)
-此处的DP类型与Severity
属性的类型不一致。应该是Register(“Severity”,typeof(Severity)
@Clemens我更新了我的post@KlausGütter谢谢你,我修复了它,但是我的控件不工作,背景也不改变。如果有一个,也就是说,尽可能小的可编译代码,但仍然可以复制problem@gittest你没能让它工作吗?