もちろん、これにアプローチする方法はたくさんあります。プログラム状態の「オブジェクト モデル」がある場合は、DataTemplates と DataTriggers を組み合わせて使用できます。これが当てはまらないと仮定すると、別のアプローチがあります。ウィンドウを参照したので、ウィンドウ クラスで「依存関係プロパティ」を次のように定義するとします。
public partial class Window1 : Window
{
public Window1()
{
this.InitializeComponent();
// Insert code required on object creation below this point.
}
public ProgramStatus ProgramStatus
{
get { return (ProgramStatus)GetValue(ProgramStatusProperty); }
set { SetValue(ProgramStatusProperty, value); }
}
// Using a DependencyProperty as the backing store for ProgramStatus. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ProgramStatusProperty =
DependencyProperty.Register("ProgramStatus", typeof(ProgramStatus), typeof(Window1), new UIPropertyMetadata(null));
}
public enum ProgramStatus
{
Normal,
Success,
Error
}
これで、ウィンドウの任意の要素 (ウィンドウ自体を含む) のほぼすべてのプロパティを、直接バインディングまたはトリガーによって変更できるようになりました。プロパティ トリガーを介してウィンドウの背景色を変更する例を次に示します。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:Test"
x:Class="Test.Window1"
x:Name="Window"
Title="Window1"
Width="640" Height="480">
<Window.Style>
<Style TargetType="{x:Type l:Window1}">
<Style.Triggers>
<Trigger Property="ProgramStatus">
<Trigger.Value>
<l:ProgramStatus>Error</l:ProgramStatus>
</Trigger.Value>
<Setter Property="Background" Value="Red" />
</Trigger>
<Trigger Property="ProgramStatus">
<Trigger.Value>
<l:ProgramStatus>Normal</l:ProgramStatus>
</Trigger.Value>
<Setter Property="Background" Value="Blue" />
</Trigger>
<Trigger Property="ProgramStatus">
<Trigger.Value>
<l:ProgramStatus>Success</l:ProgramStatus>
</Trigger.Value>
<Setter Property="Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Style>
<Grid x:Name="LayoutRoot"/>
</Window>