我想在属性更改时更改应用程序主窗口的背景颜色。我们有一个可以更改的营业日期,我想在它与预期不同时更改窗口背景。我已经设置了一个属性来说明这一点。但是我可以在改变自身的窗口上设置样式数据触发器吗?或者我需要在 app.xaml 中执行此操作吗?
问问题
18631 次
4 回答
8
我最终做了德鲁建议的事情。除了我没有使用依赖属性。
<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
是我的 Viewmodel 上由服务设置的属性。我不知道为什么这这么难。
于 2009-10-21T21:41:23.760 回答
2
如果您要在 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>
于 2009-10-20T15:11:03.630 回答
1
这是使用转换器方法的解决方案:
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
}
}
于 2009-10-20T15:17:46.527 回答
0
也许将背景与属性绑定会更好。您需要将窗口的数据源设置为对象,并且可能需要一个值转换器。
于 2009-10-20T14:51:41.757 回答