如何在C#中使用字体权重之间的相等运算符
本文关键字:之间 权重 运算符 字体 | 更新日期: 2023-09-27 18:27:24
我必须在CustomControl中创建一个FontWeight属性,但它在控制FontWeights时出错。我该如何解决?
财产登记:
public static readonly DependencyProperty FontWeightProperty =
DependencyProperty.Register(
"FontWeight",
typeof(int),
typeof(WatermarkTextBox),
new PropertyMetadata(0));
属性(我们可以更改此属性,这是我的业余工作):
private int _watermarkFontWeight = 0;
public int WatermarkFontWeight
{
get
{
if (watermarkPassTextBox.FontWeight == FontWeights.Normal)
{
_watermarkFontWeight = 0;
}
else if (watermarkPassTextBox.FontWeight == FontWeights.SemiBold)
{
_watermarkFontWeight = 1;
}
else if (watermarkPassTextBox.FontWeight == FontWeights.Bold)
{
_watermarkFontWeight = 2;
}
else if (watermarkPassTextBox.FontWeight == FontWeights.ExtraBold)
{
_watermarkFontWeight = 3;
}
return _watermarkFontWeight;
}
set
{
if (value == 0)
{
SetProperty<int>(ref _watermarkFontWeight, value, "FontWeight");
watermarkPassTextBox.FontWeight = FontWeights.Normal;
}
else if (value == 1)
{
SetProperty<int>(ref _watermarkFontWeight, value, "FontWeight");
watermarkPassTextBox.FontWeight = FontWeights.SemiBold;
}
else if (value == 2)
{
SetProperty<int>(ref _watermarkFontWeight, value, "FontWeight");
watermarkPassTextBox.FontWeight = FontWeights.Bold;
}
else if (value == 3)
{
SetProperty<int>(ref _watermarkFontWeight, value, "FontWeight");
watermarkPassTextBox.FontWeight = FontWeights.ExtraBold;
}
}
}
错误:
Operator '==' cannot be applied to operands of type 'Windows.UI.Text.FontWeight' and 'Windows.UI.Text.FontWeight'
谢谢。
根据我从文档页面上可以看出的情况(信息惊人地缺乏和/或我很难找到详细的注释),FontWeight
是一个struct
值类型,它没有为==
定义运算符,因此您无法直接比较它们。
然而,我认为您可以比较它们的底层封装Weight
值:
if (watermarkPassTextBox.FontWeight.Weight == FontWeights.Normal.Weight)
编辑:我不确定他们的Equals
实现是否有效(同样是可爱的文档),但你可以创建一个扩展方法,给你一些看起来不太好的语法:
public static bool Equals(this FontWeight weight1, FontWeight weight2)
{
return weight1.Weight == weight2.Weight;
}
导致使用:
if (watermarkPassTextBox.FontWeight.Equals(FontWeights.Normal))
_watermarkFontWeight = 0;
else if (watermarkPassTextBox.FontWeight.Equals(FontWeights.SemiBold))
_watermarkFontWeight = 1;
else if (watermarkPassTextBox.FontWeight.Equals(FontWeights.Bold))
_watermarkFontWeight = 2;
else if (watermarkPassTextBox.FontWeight.Equals(FontWeights.ExtraBold))
_watermarkFontWeight = 3;
else
return _watermarkFontWeight;
我不确定,但您可以在将转换为字符串后进行比较。。即
if (Convert.Tostring(watermarkPassTextBox.FontWeight) == Convert.Tostring(FontWeights.Normal))
{....}