我在自定义Xamarin页面中添加了BarTextColor
属性,如下所示:
public static readonly BindableProperty BarTextColorProperty = BindableProperty.Create("BarTextColor", typeof(Color), typeof(MyCustomPage), Color.Default);
public Color BarTextColor
{
get { return (Color)GetValue(BarTextColorProperty); }
set { SetValue(BarTextColorProperty, value); UpdateInnerViews(); }
}
但是当我尝试在我的App.xaml中设置一个全局样式时:
<Style TargetType="myapp:MyCustomPage">
<Setter Property="BarTextColor" Value="{StaticResource BarTextColor}"/>
</Style>
我收到此错误:
属性&#39; BarTextColor&#39;必须是要使用Setter
设置的DependencyProperty
和此:
属性&#34; BarTextColor&#34;不是DependencyProperty。用于 必须在目标类型上公开标记,非附加属性 具有可访问的实例属性&#34; BarTextColor&#34;。对于附件 属性,声明类型必须提供静态&#34; GetBarTextColor&#34; 和&#34; SetBarTextColor&#34;方法
出了什么问题? github上的Xamarin源都使用BindableProperty
而非DependencyProperty
,为什么我不能使用?
(我使用Visual Studio Community 2013和Xamarin 2.3.1,如果重要的话)
答案 0 :(得分:2)
我创建了BasePage.cs
:
public class BasePage : ContentPage
{
public static readonly BindableProperty BarTextColorProperty =
BindableProperty.Create(nameof(BarTextColor),
typeof(Color),
typeof(BasePage),
Color.White,
propertyChanged: OnColorChanged);
private static void OnColorChanged(BindableObject bindable, object oldValue, object newValue)
{
}
public Color BarTextColor
{
get { return (Color)GetValue(BarTextColorProperty); }
set { SetValue(BarTextColorProperty, value); }
}
}
然后创建了一些ContentPage
:
<local:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SuperForms.Samples.CustomPropertySample;assembly=SuperForms.Samples"
x:Class="SuperForms.Samples.CustomPropertySample.Page1"
Style="{StaticResource BasePageStyle}">
<Label Text="Alloha" VerticalOptions="Center" HorizontalOptions="Center" />
</local:BasePage>
public partial class Page1 : BasePage
{
public Page1()
{
InitializeComponent();
}
}
并在Style
中声明App.xaml
:
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:customPropertySample="clr-namespace:SuperForms.Samples.CustomPropertySample;assembly=SuperForms.Samples"
x:Class="SuperForms.Samples.App">
<Application.Resources>
<ResourceDictionary>
<Style x:Key="BasePageStyle" TargetType="customPropertySample:BasePage">
<Setter Property="BarTextColor" Value="#ff0000"/>
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
但我使用了Style
Key
,因为它不适用于Key
。
在OnColorChanged
Style
上我有红色。
<强>被修改强>
或者您可以创建导航基页:
public class BaseNavigationPage : NavigationPage
{
public BaseNavigationPage(ContentPage root)
: base(root)
{
}
public BaseNavigationPage()
{
BarBackgroundColor = Color.Red;
}
}
并将其用于导航:
public App()
{
InitializeComponent();
MainPage = new CustomPropertySample.BaseNavigationPage(new CustomPropertySample.Page1());
}