您可以使用绑定转换器执行此操作。
http://tech.pro/tutorial/806/wpf-tutorial-binding-converters
或者,可能更容易实现,触发器。
http://wpftutorial.net/Triggers.html
编辑(一些示例):
绑定转换器示例 - 仅在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" />