当然,有很多方法可以解决这个问题。如果您有一个程序状态“对象模型”,您可以使用 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>