gpt4 book ai didi

c# - 颜色 TextBlock 取决于枚举值

转载 作者:行者123 更新时间:2023-12-03 10:54:10 25 4
gpt4 key购买 nike

我正在使用 MvvM 模型研究 WPF。

我有一个包含 Texblocks 的 View 。它显示有关 ID 的信息(来自文档和数据库):

<GroupBox Grid.Row="1" Grid.Column="0" Header="ID Informations">
<StackPanel Orientation="Vertical">
<TextBlock Text="DataBase surname: "/>
<TextBlock Text="{Binding Model.Db_SURNAME}" FontWeight="Bold"/>
<TextBlock Text="Document surname: "/>
<TextBlock Text="{Binding Model.Dc_SURNAME}" FontWeight="Bold"/>
<TextBlock Text="DataBase forename: "/>
<TextBlock Text="{Binding Model.Db_FORENAME}" FontWeight="Bold"/>
<TextBlock Text="Document forename: "/>
<TextBlock Text="{Binding Model.Dc_FORENAME}" FontWeight="Bold"/>
</StackPanel>
</GroupBox>

我有一个包含错误代码的枚举:
[Flags]
public enum errorID
{
OK = 1<<0,
SURNAME_DIFF = 1 << 1,
FORENAME_DIFF = 1 << 2
}

我的模型是这样写的:
private String _db_SURNAME;
public String Db_SURNAME
{
get { return _db_SURNAME; }
set { SetProperty(ref _db_SURNAME, value); }
}
[...]

private errorID _errorID;
public errorID ErrorID
{
get { return _errorID; }
set { SetProperty(ref _errorID, value); }
}

我希望我的两个文本 block 都显示 Model.Db_SURNAMEModel.Dc_SURNAME ErrorID.HasFlag(errorID.SURNAME_DIFF ) .也适用于 Forname .

我能怎么做 ?

最佳答案

使用转换器将您的枚举转换为如下颜色:

public class ErrorIdColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(!(value is errorID))
throw new ArgumentException("value not of type errorID");
if(!(parameteris errorID))
throw new ArgumentException("parameter not of type errorID");

errorID error = (errorID)value;
errorID flag = (errorID)parameter;

if (error.HasFlag(flag))
{
return Brushes.Red;
}
...

return Brushes.Black;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
....
}

}

然后您可以使用转换器将前景色绑定(bind)到您的枚举:
<TextBlock Text="{Binding Model.Db_SURNAME}" FontWeight="Bold" Foreground={Binding Model.errorId, Converter={StaticRessource errorIDColorConverter}, ConverterParameter={StaticRessource errorID.SURNAME_DIFF}}/>

关于c# - 颜色 TextBlock 取决于枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52271449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com