我的窗口上有一个按钮。默认情况下,按钮的背景颜色为蓝色。单击按钮时,颜色应更改为红色。但我看到背景颜色正在变为红色,但它不是永久性的。
这是课程代码:
/// <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
}
xml代码:
<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>
我会很感激这里的任何帮助。