gpt4 book ai didi

c# - 有什么方法可以在 Xamarin.Forms 中将样式与我的 XAML 分开

转载 作者:可可西里 更新时间:2023-11-01 09:10:05 26 4
gpt4 key购买 nike

我在带有 XAML 页面的 PCL 中使用 Xamarin.Forms。我想出给我的控件设置样式的唯一方法是使用内联语法。

<Button Text="Inquiry" TextColor="Blue" />

我更愿意使用这样的结构:

<Page.Resources>
<Style TargetType="Button">
<Setter Property="BorderThickness" Value="5" />
<Setter Property="Foreground" Value="Blue" />
</Style>
</Page.Resources>

( http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh465381.aspx )

但是,(尚)不支持 Style 元素。有没有人成功地将布局与内容分开?

仅供引用:我还在 Xamarin 论坛中发布了这个问题,所以任何通过谷歌来到这里的人可能还想看看这个页面:http://forums.xamarin.com/discussion/19287/styling-of-xamarin-xaml#latest

最佳答案

风格并不那么难[需要引用]。您可以自己实现,就像我刚刚为了这个答案所做的那样。

这是 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);
}
}
}

显然,执行赋值的代码非常简单,您可能必须根据需要对其进行调整(支持枚举等),但它适用于这种简单的情况。

我相信它会有所帮助。

关于c# - 有什么方法可以在 Xamarin.Forms 中将样式与我的 XAML 分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24425757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com