我的窗户上有一个按钮。默认情况下,按钮的背景颜色为蓝色。单击按钮时,颜色应更改为红色。但我发现背景颜色正在变为红色但不是永久性的。
这是类代码:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
bool _highLow;
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
_highLow = false;
}
public bool RiskHighLowMedium
{
get { return _highLow; }
set { _highLow= value ;
this.OnPropertyChanged("RiskHighLowMedium");
this.OnPropertyChanged("BackGround");
}
}
//background Dependency Property
public static readonly DependencyProperty BackgroundProperty;
/// <summary>
/// static constructor
/// </summary>
static MainWindow()
{
BackgroundProperty = DependencyProperty.Register("Background", typeof(Brush), typeof(MainWindow));
}
/// <summary>
/// Background Dependency
/// Property
/// </summary>
public Brush Background
{
get { return (Brush)GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
RiskHighLowMedium = true;
Background = RiskHighLowMedium ? Brushes.Red : Brushes.Blue;
this.OnPropertyChanged("RiskHighLowMedium");
this.OnPropertyChanged("Background");
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion // INotifyPropertyChanged Members
}
xaml代码:
<Window x:Class="backgrounChange.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="CircleButton" TargetType="Button">
<Setter Property="Background" Value="Blue"/>
<Style.Triggers>
<DataTrigger Binding="{Binding RiskHighLowMedium }" Value="true">
<Setter Property="Background" Value="{ Binding Path= Background}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Button Width="50" Height="50" Style="{DynamicResource CircleButton}" Click="Button_Click"/>
</Grid>
</Window>
我很感激这里的任何帮助。
答案 0 :(得分:1)
虽然您可以更改Button.Background
值,但ControlTemplate
控件的默认Button
定义了一个动画,可动画显示官方{{1}之间Button
的背景。值和另一种(浅蓝色)颜色。要摆脱这种行为,您必须为Button.Background
定义新的ControlTemplate
。这是一个非常的基本示例:
Button