我可以使用:
<TextBlock Text="Some Textes" FontSize="12pt" />
可以正常使用。但我想使用DynamicResource
扩展,可以吗?
这不起作用:
<TextBlock Text="Some Textes" FontSize="{DynamicResource SomeResources}" />
一些资源:
<System:Stringx:Key="SomeResources">12pt</System:String>
我不想使用AttachedBehavior
。我知道,我可以用它解决我的问题(使用 FontSizeConverter
)。
最佳答案
更新:
我看到您已经编辑了您的问题并删除了绑定(bind)选项。如果您只想从 xaml 资源获取此信息,则需要使用 MarkupExtension
。您可以找到 MarkupExtension
和用法 here 。这对于你的情况来说效果很好。
原始回复:
FontSize
的类型为 System:Double
Documentation .
FontSize
的下一个默认 Binding
假设像素处于与设备无关的比例,但由于您需要 pt,我们可以使用转换器,例如:
using System.Globalization;
using System.Windows;
using System.Windows.Data;
class ConvertFromPoint : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
var convertFrom = new FontSizeConverter().ConvertFrom(value.ToString());
if (convertFrom != null)
return (double) convertFrom;
return 1;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
和用法:
<TextBlock FontSize="{Binding StringProperty, Converter={StaticResource ConvertFromPointConverter}}">Some Text</TextBlock>
替代:
如果您不想使用转换器和 FontSizeConverter
,只需在属性 getter 中进行计算即可。
类似于:
private double _someFontval;
public double SomeFontVal {
get {
return _someFontval * 96 / 72;
}
set {
_someFontval = value;
}
}
用法:
//.cs
SomeFontVal = 12.0;
//.xaml
<TextBlock FontSize="{Binding SomeFontVal}">Some Text</TextBlock>
关于WPF如何通过DynamicResource为FontSize属性设置pt(12pt等..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16774122/