値に応じた色付けをするような時、画面コントロールではなくてLabel部品側で色をつけたいところ
Styleを作る
<?xml version="1.0" encoding="UTF-8"?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:common="clr-namespace:hoge.Common"
x:Class="hoge.Asset.Styles">
<x:Double x:Key="DefaultFontSize">16</x:Double>
<Color x:Key="DefaultTextColor">#000000</Color>
<Style x:Key="RegularFontStyle" TargetType="Label">
<Setter Property="FontSize" Value="{StaticResource DefaultFontSize}" />
<Setter Property="TextColor" Value="{StaticResource DefaultTextColor}" />
</Style>
<Style TargetType="common:ValueLabel" BasedOn="{StaticResource RegularFontStyle}">
</Style>
</ResourceDictionary>
ここでは自動着色するLabelをcommon:ValueLabel
として定義してます
起動時にスタイルを読み込む
<?xml version="1.0" encoding="utf-8"?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:theme="clr-namespace:hoge.Asset"
x:Class="hoge.App">
<Application.Resources>
<theme:Styles />
</Application.Resources>
</Application>
App.xamlで読み込む
Labelクラスを作る
using System;
using System.Runtime.CompilerServices;
using Xamarin.Forms;
namespace hoge.Common
{
public class ValueLabel : Label
{
public ValueLabel()
{
}
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == "Text")
{
if (!string.IsNullOrEmpty(Text) && Text.Contains("+"))
{
TextColor = (Color)App.GetStyle()["PlusColor"];
}
else if (!string.IsNullOrEmpty(Text) && Text.Contains("-"))
{
TextColor = (Color)App.GetStyle()["MinusColor"];
}
}
}
}
}
数値処理は省略してますが、とりあえず+かーかが含まれてたら色をつけるというロジックにしてます
OnPropertyChanged
での判定が楽なのでこんな処理にしてますがパフォーマンスはあまり良くないと思います