shuhelohelo’s blog

Xamarin.Forms多めです.

XAMLからクラスのStaticプロパティにアクセスする方法

docs.microsoft.com

マークアップ拡張のx:staticを使うとクラスのStaticプロパティにアクセスできる.

f:id:shuhelohelo:20191129000028p:plain

例えば,こんなクラスを定義しておく.

    public class SharedSources2
    {
        public static string MyTestProperty2 => "Hello World";
    }

そして,XAML側では最上位の要素(ContentPageなど)に名前空間を追加する. 上から3行目のxmlns:local2="clr-namespace:Phoneword2"

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local2="clr-namespace:Phoneword2"
             x:Class="Phoneword.MainPage">

そうすると,同じくXAML内で以下のようにしてアクセスできる.

        <Button x:Name="callButton" Text="{x:Static local:SharedSources2.MyTestProperty2}" IsEnabled="false" Clicked="OnCall" />