使用Xamarin.Forms中的View Model属性绑定到StaticResource? [英] Binding to StaticResource with a property of View Model in Xamarin.Forms?
问题描述
我在ResourceDictionary中定义了一些自定义字体
I have some custom fonts defined in 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绑定切换FontFamily,就像FontSize的绑定一样,因为CurrentFontSize是View模型中的一个属性. 我尝试过:
So far so good. However, I would switch the FontFamily at runtime through ViewModel binding just like the binding for FontSize, since CurrentFontSize is a property in the View Model. I had tried:
FontFamily="{Binding CurrentFontFamily}"
并且CurrentFontFamily的值可以指向现有的系统字体,但是我想指向一个自定义字体,该字体指向ResourceDictionary中定义的字体.
And the value of CurrentFontFamily can point to an existing system font, but I want to point to a custom font pointing to what defined in ResourceDictionary.
然后我尝试了:
FontFamily="{StaticResource {Binding CurrentFontFamily}}"
显然,针对这种构成语法存在运行时错误.我只是想知道XAML中是否存在通过MVVM View Model在运行时切换自定义字体的方法?
And there's runtime error obviously against such makeup syntax. I just wonder whether there's a in XAML to switch custom font at runtime through MVVM View Model?
推荐答案
Data Trigger is the way to go, as explained in https://blog.xamarin.com/triggers-in-xamarin-forms/. Following the example there, now I have:
<Label Text="{Binding CurrentText}" Grid.Column="1" Margin="5,0,0,0"
FontSize="{Binding CurrentFontSize}" TextColor="Black"
HorizontalTextAlignment="Start" VerticalTextAlignment="Center">
<Label.Triggers>
<DataTrigger TargetType="Label"
Binding="{Binding Source={x:Reference fontSelected}, Path=SelectedIndex}"
Value="0">
<Setter Property="FontFamily" Value="{StaticResource NormalFont}"/>
</DataTrigger>
<DataTrigger TargetType="Label"
Binding="{Binding Source={x:Reference chartSelected}, Path=SelectedIndex}"
Value="1">
<Setter Property="FontFamily" Value="{StaticResource SuperFont}"/>
</DataTrigger>
</Label.Triggers>
</Label>
这篇关于使用Xamarin.Forms中的View Model属性绑定到StaticResource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!