是否可以将Xamarin Forms中的静态资源进行数据绑定? 像
Style="{StaticResource {Binding foo, StringFormat='SomeStyle{0}'}}"
谢谢
答案 0 :(得分:1)
您可能想要的是一个值转换器,它可以为您查找StaticResource。完整的Microsoft文档here。
在XAML元素上,您将执行以下操作:
<Entry Style="{Binding foo, Converter={StaticResource FooToStyleConverter}}"/>
您的转换器将像这样工作:
public class FooToStyleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var someValue = (string)value; // Convert 'object' to whatever type you are expecting
// evaluate the converted value
if (someValue != null && someValue == "bar")
return (Style)App.Current.Resources["StyleOne"]; // return the desired style
return (Style)App.Current.Resources["StyleTwo"];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Usually unused, but inverse the above logic if needed
throw new NotImplementedException();
}
}
最后,将您的转换器设置为App.xaml中的静态资源(或页面上的本地资源),以便您的页面可以正确地引用它。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DataBindingDemos">
<ContentPage.Resources>
<ResourceDictionary>
<local:FooToStyleConverter x:Key="FooToStyleConverter" />
....