SolidColorBrush bgColor;
public ModernBTN() {
InitializeComponent();
this.Loaded += delegate (object sender, RoutedEventArgs e) {
bgColor = (SolidColorBrush)Background;
MouseEnter += EnterAnim;
MouseLeave += LeaveAnim;
};
}
private void EnterAnim(object sender, MouseEventArgs e) {
DoubleAnimation anim = new DoubleAnimation(0, myBtn.Width, TimeSpan.FromMilliseconds(200));
indicatorBtn.BeginAnimation(WidthProperty, anim);
ColorAnimation animC = new ColorAnimation(BGHover, TimeSpan.FromMilliseconds(200));
myBtn.Background.BeginAnimation(SolidColorBrush.ColorProperty, animC);
}
private void LeaveAnim(object sender, MouseEventArgs e) {
DoubleAnimation anim = new DoubleAnimation(myBtn.Width, 0, TimeSpan.FromMilliseconds(200));
indicatorBtn.BeginAnimation(WidthProperty, anim);
ColorAnimation animC = new ColorAnimation(Color.FromArgb(bgColor.Color.A, bgColor.Color.R, bgColor.Color.G, bgColor.Color.B), TimeSpan.FromMilliseconds(200));
myBtn.Background.BeginAnimation(SolidColorBrush.ColorProperty, animC);
}
请告诉我如果我仅将bgColor值放在此中,为什么bgColor会变为BGHover颜色.Loaded和=(SolidColorBrush)Background。
我的按钮的ModernBtn.xaml xaml代码
<UserControl x:Class="ModernButton.ModernBTN"
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:ModernButton"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="200" Name="myBtn" Background = '#FF282829'>
<Grid Width="Auto" Height="Auto" Name="mainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="{Binding ElementName=myBtn, Path=BtnText}" FontSize="24" Foreground="#FFC7BBBB" TextAlignment="Center" Grid.Row="0" Name="txtBtn" Padding="{Binding ElementName=myBtn, Path=TextPadding}"></TextBlock>
<Rectangle Grid.Row="1" Fill="Lime" Height="5" Name="indicatorBtn" Width="0"></Rectangle>
</Grid>
答案 0 :(得分:1)
bgColor =(SolidColorBrush)Background;
由于SolidColorBrush
是引用类型,因此bgColor
和Background
将在上一行之后引用同一对象。因此,当对Background
进行更改时(就像您对动画所做的那样),此更改将反映在bgColor
中。
解决此问题的一种简单方法是将bgColor
更改为键入Color
:
Color bgColor;
public MainWindow()
{
InitializeComponent();
this.Loaded += delegate (object sender, RoutedEventArgs e) {
bgColor = ((SolidColorBrush)Background).Color;
MouseEnter += EnterAnim;
MouseLeave += LeaveAnim;
};
}
private void EnterAnim(object sender, MouseEventArgs e)
{
ColorAnimation animC = new ColorAnimation(BGHover, TimeSpan.FromMilliseconds(200));
myBtn.Background.BeginAnimation(SolidColorBrush.ColorProperty, animC);
}
private void LeaveAnim(object sender, MouseEventArgs e)
{
ColorAnimation animC = new ColorAnimation(bgColor, TimeSpan.FromMilliseconds(200));
myBtn.Background.BeginAnimation(SolidColorBrush.ColorProperty, animC);
}