c# - 使用 Xamarin.Forms 中的 View 模型属性绑定(bind)到 StaticResource?

标签 c# android xaml 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>

  <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/

相关文章:

c# - RestSharp 获取请求的完整 URL

c# - 在 Silverlight 中,如何将 ListBox 项目选择绑定(bind)到 Navigate 事件?

java 任务 ':app:transformResourcesWithMergeJavaResForDebug' 执行失败

android - LiveData 和 Coroutines - 属性必须被初始化或抽象

WPF:没有文本时将 TextBlock 高度设置为 0

c# - Asp.Net SQL删除语句

c# - 如何返回能够在服务器上执行的对象?

android - 如何将音频文件存储到android的内部存储中

xaml - 如何获取ContentPage xamarin.forms中ContentView页面按钮的点击事件

silverlight - 如何对齐文本,使其位于 Silverlight 中按钮的中间?