LoginSignup
0
1

More than 5 years have passed since last update.

Xamarin.Formsで数値の±で着色するLabelを作る

Posted at

値に応じた色付けをするような時、画面コントロールではなくて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での判定が楽なのでこんな処理にしてますがパフォーマンスはあまり良くないと思います

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1