使用 Xamarin.Forms 中的 View Model 属性绑定到 StaticResource?

ZZZ*_*ZZZ 4 c# xaml android mvvm xamarin.forms

我在 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>
Run Code Online (Sandbox Code Playgroud)

  <Label Text="{Binding CurrentOptotype.Text}" FontFamily="{StaticResource SuperFont}" FontSize="{Binding CurrentFontSize}" TextColor="Black" />
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好。但是,我会在运行时通过 ViewModel 绑定切换 FontFamily,就像 FontSize 的绑定一样,因为 CurrentFontSize 是视图模型中的一个属性。我试过:

FontFamily="{Binding CurrentFontFamily}"
Run Code Online (Sandbox Code Playgroud)

CurrentFontFamily 的值可以指向现有的系统字体,但我想指向一个自定义字体,指向 ResourceDictionary 中定义的字体。

我当时尝试过:

FontFamily="{StaticResource {Binding CurrentFontFamily}}"
Run Code Online (Sandbox Code Playgroud)

并且对于这种化妆语法显然存在运行时错误。我只是想知道 XAML 中是否有一个在运行时通过 MVVM 视图模型切换自定义字体?

Dan*_*iel 5

你试过这个吗?

FontFamily="{Binding CurrentFontFamily}"
Run Code Online (Sandbox Code Playgroud)

编辑:

您可以使用转换器执行此操作:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的 App.xaml 中,添加您的转换器:

<Application.Resources>
    <ResourceDictionary>
        ....
        <extensions:FontConverter x:Key="FontConverter"/>
    </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

然后你可以绑定你的财产

FontFamily={Binding FontName, Converter={StaticResource FontConverter}}
Run Code Online (Sandbox Code Playgroud)