I created hierarchy of controls for my project: abstract BaseSettingsElement
and inherited EntrySettingsElement
, PickerSettingsElement
, SwitchSettingsElement
etc. The base class provide the properties to change text, color, font of header/subheader. Example of property declaration:
public static readonly BindableProperty HeadTextColorProperty =
BindableProperty.Create("HeadTextColor", typeof(Color), typeof(BaseSettingsElement), Color.FromHex("#ffffff"),
propertyChanged: (bindable, oldValue, newValue) =>
{
(bindable as BaseSettingsElement).headText.TextColor = (Color)newValue;
});
//...
public Color HeadTextColor
{
get { return (Color)GetValue(HeadTextColorProperty); }
set { SetValue(HeadTextColorProperty, value); }
}
There is no problem when I'm creating this controls in xaml and apply some properties to them:
<custom:EntrySettingsElement Grid.Row="16"
InputType="Number"
DividersVisibility="None"
IsEnabled="False"
HeadTextColor="Red"
Text="0" />
But when I'm trying to apply a global style in app.xaml to some of my controls I have a NullRefferenceException
here:
public static readonly BindableProperty HeadTextColorProperty =
BindableProperty.Create("HeadTextColor", typeof(Color), typeof(BaseSettingsElement), Color.FromHex("#ffffff"),
propertyChanged: (bindable, oldValue, newValue) =>
{
(bindable as BaseSettingsElement).headText.TextColor = (Color)newValue;
//Here is a NullReferenceException: bindable object is not null but the field 'headText' is null...
});
Just in case the xaml of the base control:
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="RemoteControlApp.CustomViews.BaseSettingsElement"
xmlns:custom="clr-namespace:RemoteControlApp.CustomViews;assembly=RemoteControlApp">
<ContentView.Content>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<custom:Divider x:Name="topDivider"
Grid.Row="0"
Grid.ColumnSpan="2"
BackgroundColor="{StaticResource grayColor}" />
<StackLayout x:Name="container"
Orientation="Vertical"
Spacing="0"
Grid.Column="0"
Margin="15,12,0,12"
Grid.Row="1"
VerticalOptions="Center">
<Label x:Name="headText" />
<Label x:Name="bodyText" />
</StackLayout>
<custom:Divider x:Name="bottomDivider"
Grid.Row="2"
Grid.ColumnSpan="2"
BackgroundColor="{StaticResource grayColor}" />
<ContentView x:Name="asideContainer"
Margin="0,0,15,0"
Grid.Column="1"
Grid.Row="1" />
</Grid>
</ContentView.Content>
</ContentView>