我在 ResourceDictionary 中定义了一些自定义字体
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Fonlow.VA.App">
<Application.Resources>
<ResourceDictionary>
<OnPlatform x:TypeArguments="x:String" x:Key="SuperFont">
<On Platform="Android" Value="Super.ttf#Super" />
<On Platform="UWP" Value="/Assets/Super.ttf#Super" />
<!--<On Platform="iOS" Value="OpenSans-Bold" />-->
</OnPlatform>
<OnPlatform x:TypeArguments="x:String" x:Key="NormalFont">
<On Platform="Android" Value="Normal.ttf#Normal" />
<On Platform="UWP" Value="/Assets/Normal.ttf#Normal" />
<!--<On Platform="iOS" Value="OpenSans-Bold" />-->
</OnPlatform>
</ResourceDictionary>
</Application.Resources>
和
<Label Text="{Binding CurrentOptotype.Text}" FontFamily="{StaticResource SuperFont}" FontSize="{Binding CurrentFontSize}" TextColor="Black" />
到目前为止一切顺利。但是,我会在运行时通过 ViewModel 绑定(bind)切换 FontFamily,就像 FontSize 的绑定(bind)一样,因为 CurrentFontSize 是 View 模型中的一个属性。 我试过:
FontFamily="{Binding CurrentFontFamily}"
而 CurrentFontFamily 的值可以指向一个现有的系统字体,但我想指向一个自定义字体,指向 ResourceDictionary 中定义的字体。
然后我尝试了:
FontFamily="{StaticResource {Binding CurrentFontFamily}}"
并且显然存在针对此类化妆语法的运行时错误。我只是想知道 XAML 中是否有通过 MVVM View 模型在运行时切换自定义字体的功能?
最佳答案
你试过吗?
FontFamily="{Binding CurrentFontFamily}"
编辑:
您可以使用转换器来做到这一点:
public class FontConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var fontName = value as string;
if(!Application.Current.Resources.ContainsKey(fontName))
throw new KeyNotFoundException($"{fontName} not found in resources");
return (string) Application.Current.Resources[fontName];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
在您的 App.xaml 中,添加您的转换器:
<Application.Resources>
<ResourceDictionary>
....
<extensions:FontConverter x:Key="FontConverter"/>
</ResourceDictionary>
</Application.Resources>
然后你就可以绑定(bind)你的属性了
FontFamily={Binding FontName, Converter={StaticResource FontConverter}}
关于c# - 使用 Xamarin.Forms 中的 View 模型属性绑定(bind)到 StaticResource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52165202/