风格并不难[需要引用]。您可以实现自己的,就像我刚刚为这个答案所做的那样。
下面是 Xaml 的外观:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:YourNS;assembly=YourAssembly">
<ContentPage.Resources>
<ResourceDictionary>
<local:Style x:Key="buttonStyle">
<local:Setter Property="BorderWidth" Value="5"/>
</local:Style>
</ResourceDictionary>
</ContentPage.Resources>
<Button Text="Foo" local:Style.Style="{StaticResource buttonStyle}" x:Name="button"/>
</ContentPage>
支持代码如下所示:
namespace YourNS
{
public class Setter {
public string Property { get; set; }
public string Value { get; set; }
}
[ContentProperty ("Children")]
public class Style
{
public Style ()
{
Children = new List<Setter> ();
}
public IList<Setter> Children { get; private set; }
public static readonly BindableProperty StyleProperty =
BindableProperty.CreateAttached<Style, Style> (bindable => GetStyle (bindable), default(Style),
propertyChanged: (bindable, oldvalue, newvalue)=>{
foreach (var setter in newvalue.Children) {
var pinfo = bindable.GetType().GetRuntimeProperty (setter.Property);
pinfo.SetMethod.Invoke (bindable,new [] {Convert.ChangeType (setter.Value, pinfo.PropertyType.GetTypeInfo())});
}
});
public static Style GetStyle (BindableObject bindable)
{
return (Style)bindable.GetValue (StyleProperty);
}
public static void SetStyle (BindableObject bindable, Style value)
{
bindable.SetValue (StyleProperty, value);
}
}
}
显然,执行分配的代码非常简单,您可能需要根据您的需要对其进行调整(支持枚举等),但它适用于这种简单化的情况。
我相信它会有所帮助。