gpt4 book ai didi

c# - 根据背景颜色更改按钮的鼠标悬停颜色

转载 作者:行者123 更新时间:2023-12-02 04:19:50 25 4
gpt4 key购买 nike

我一直在试图弄清楚如何更改按钮的悬停颜色,我发现 this :

但这只是我想要实现的目标的一半。我想根据当前背景颜色更改悬停颜色。即

默认按钮背景颜色:灰色

我点击它,按钮的背景颜色将变成红色。悬停颜色应更改为粉红色。

我再次单击它,按钮的背景颜色将变为绿色。悬停颜色应更改为浅绿色。

这在标记和代码隐藏中可能吗?怎么办?

最佳答案

XAML:

<Button Content="Color change" Background="{Binding BackGround}" Command="{Binding ButtonPressedCommand}">
<Button.Template>
<ControlTemplate TargetType="Button">
<Border Name="Border" Background="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background, Mode=OneWay}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" TargetName="Border"
Value="{Binding BackGroundOnHover}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Background" TargetName="Border"
Value="{Binding BackGround}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>

View 模型:

class MainViewModel : INotifyPropertyChanged
{
private Brush _backGround = new SolidColorBrush(Colors.Red);

public Brush BackGround
{
get { return _backGround; }
set
{
_backGround = value;
OnPropertyChanged();
}
}

private Brush _backGroundOnHover;
public Brush BackGroundOnHover
{
get
{
if (_backGroundOnHover == null)
SetHoverBackGround();
Debug.WriteLine(((SolidColorBrush)_backGroundOnHover).Color.R);
return _backGroundOnHover;
}
set
{
_backGroundOnHover = value;
OnPropertyChanged();
}
}

private RelayCommand _buttonPressedCommand;

public RelayCommand ButtonPressedCommand
{
get
{
return _buttonPressedCommand ??
(_buttonPressedCommand = new RelayCommand(SetBackgroundWhenButtonPressed));
}
}

private void SetBackgroundWhenButtonPressed()
{
var color = ((SolidColorBrush)BackGround).Color;
BackGround = new SolidColorBrush(Color.FromRgb((byte)(color.R - 5), color.G, color.B));
SetHoverBackGround();
}

private void SetHoverBackGround()
{
var color = ((SolidColorBrush)BackGround).Color;
BackGroundOnHover = new SolidColorBrush(Color.FromRgb((byte)(255-color.R ), color.G, color.B));
}


public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

public event PropertyChangedEventHandler PropertyChanged;
}

每当您单击时,它都会更改背景颜色,并在鼠标悬停时同时更改颜色。

关于c# - 根据背景颜色更改按钮的鼠标悬停颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com