Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

Organization

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?