您可以使用绑定转换器来做到这一点。
http://tech.pro/tutorial/806/wpf-tutorial-binding-converters
或者,也许更容易实现,触发器。
http://wpftutorial.net/Triggers.html
编辑(一些例子):
Binding Converter Sample - 仅在 UserControl 上,但应该显示它是如何完成的。
在 UCButton.xaml.cs 中:
using System;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace Test3
{
public partial class UCButton : UserControl
{
public UCButton()
{
InitializeComponent();
this.DataContext = this;
}
}
[ValueConversion(typeof(Brush), typeof(Brush))]
public class BrushConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
Brush background = (Brush)value;
if (background == Brushes.Pink)
return Brushes.Red;
else if (background == Brushes.LightBlue)
return Brushes.DarkBlue;
else if (background == Brushes.LightGreen)
return Brushes.DarkGreen;
else
return Brushes.Black;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
UCButton.xaml
<UserControl x:Class="Test3.UCButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Test3" mc:Ignorable="d"
d:DesignHeight="29" d:DesignWidth="82">
<UserControl.Resources>
<local:BrushConverter x:Key="brushConverter" />
</UserControl.Resources>
<Grid>
<Button Content="Button" Name="button1" Background="{Binding Background}" Foreground="{Binding Background, Converter={StaticResource brushConverter}}" />
</Grid>
</UserControl>
使用触发器的示例:
在 MainWindow.xaml 添加:
<Window.Resources>
<Style x:Key="buttonBrushStyle" TargetType="Button">
<Style.Triggers>
<Trigger Property="Background" Value="Pink">
<Setter Property="Foreground" Value="Red" />
</Trigger>
<Trigger Property="Background" Value="LightBlue">
<Setter Property="Foreground" Value="DarkBlue" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Button Style="{StaticResource buttonBrushStyle}" Content="Button"
Height="23" Width="75" Background="Pink" />
<Button Style="{StaticResource buttonBrushStyle}" Content="Button"
Height="23" Width="75" Background="LightBlue" />