当属性改变时,我希望更改我们应用程序主窗口的背景颜色。我们有一个可以更改的业务日期,当它与预期不同时,我想更改窗口背景。我已经设置了一个属性来告知此情况。但是,我能否在窗口上设置样式数据触发器以自行更改?还是需要在app.xaml中进行?
当属性改变时,我希望更改我们应用程序主窗口的背景颜色。我们有一个可以更改的业务日期,当它与预期不同时,我想更改窗口背景。我已经设置了一个属性来告知此情况。但是,我能否在窗口上设置样式数据触发器以自行更改?还是需要在app.xaml中进行?
我最终做的有点像Drew建议的。 但我没有使用依赖属性。
<Window.Resources>
<SolidColorBrush x:Key="windowBGBrush" Color="Green"/>
<SolidColorBrush x:Key="windowBGBrushBusinessDateChanged" Color="Red"/>
</Window.Resources>
<Window.Style >
<Style TargetType="{x:Type Window}">
<Setter Property="Background" Value="{DynamicResource windowBGBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsBusinessDateChanged}" Value="true">
<Setter Property="Background" Value="{DynamicResource windowBGBrushBusinessDateChanged}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Style>
IsBusinessDateChanged
是我视图模型上的一个属性,由服务设置。我不确定为什么这样做很困难。
如果您在 Window 上公开自定义属性,请确保将其定义为 DependencyProperty,然后您应该能够在样式中使用常规触发器来响应属性。就像这样:
<Window.Style>
<Style TargetType="{x:Type MyWindow}">
<Style.Triggers>
<Trigger Property="MyProperty" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Style>
这里提供一种使用转换器方法的解决方案:
XAML:
<Window x:Class="StackOverflowTests.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" x:Name="window1" Width="300"
xmlns:local="clr-namespace:StackOverflowTests">
<Window.Resources>
<local:DateToColorConverter x:Key="DateToColorConverter" />
</Window.Resources>
<Window.Background>
<SolidColorBrush Color="{Binding ElementName=textBoxName, Path=Text, Converter={StaticResource DateToColorConverter}}" />
</Window.Background>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox x:Name="textBoxName" Margin="5"></TextBox>
</Grid>
</Window>
C#:
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace StackOverflowTests
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
public class DateToColorConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DateTime date;
if (DateTime.TryParse(value.ToString(), out date))
{
if (date == DateTime.Today)
return Colors.Green;
else
return Colors.Red;
}
else
{
return Colors.Gold;
}
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotImplementedException();
}
#endregion
}
}