[xaml]xamlで定数を使う


やりたいこと

C言語でいうところの「#define (100)」みたいな感じで定数を定義して、同じ定数を割り当てたものは一括して乗数変更できるようにしたい。

やり方

xmlns:sys="clr-namespace:System;assembly=mscorlib"を使う。

サンプルコード

MainWindow.xaml
<Window x:Class="WpfApp20.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp20"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"★これを追加
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="200">
    <Window.Resources>
        <!-- 定数定義部分。Keyをつけて、下で使う-->
        <sys:Double x:Key="EllipseWidth">20.0</sys:Double>
        <sys:Boolean x:Key="ButtonEnable">true</sys:Boolean>
        <sys:String x:Key="ButtonText">ボタン</sys:String>
    </Window.Resources>

    <StackPanel Orientation="Horizontal">
        <!-- 定数使用部分。上で定義した定数をKeyで紐づける-->
        <Ellipse Width="{StaticResource EllipseWidth}" Stroke="Red"/>
        <Ellipse Width="{StaticResource EllipseWidth}" Stroke="Red"/>
        <Ellipse Width="{StaticResource EllipseWidth}" Stroke="Red"/>
        <Ellipse Width="{StaticResource EllipseWidth}" Stroke="Red"/>
        <Ellipse Width="{StaticResource EllipseWidth}" Stroke="Red"/>
        <Button Content="{StaticResource ButtonText}" IsEnabled="{StaticResource ButtonEnable}"/>
    </StackPanel>
</Window>